* health check

* Update Dockerfile

* simplifying the deployment

* Update Bot.js

makes the find team command public

* test (#9)

* Dev (#7)

* health check

* Update Dockerfile

* simplifying the deployment

* Dev (#8)

* health check

* Update Dockerfile

* simplifying the deployment

* Update Bot.js

makes the find team command public

* Update PlayerService.js

* massive update????

could break stuff

* Update Bot.js

update
This commit is contained in:
VinceC
2025-07-07 21:38:19 -05:00
committed by GitHub
parent 0c86148835
commit 3453be6947
1742 changed files with 28844 additions and 67711 deletions

4
node_modules/@types/node/README.md generated vendored
View File

@@ -8,8 +8,8 @@ This package contains type definitions for node (https://nodejs.org/).
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Sat, 14 Sep 2024 00:53:13 GMT
* Last updated: Sat, 28 Jun 2025 07:33:25 GMT
* Dependencies: [undici-types](https://npmjs.com/package/undici-types)
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky).
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig).

34
node_modules/@types/node/assert.d.ts generated vendored
View File

@@ -1,7 +1,7 @@
/**
* The `node:assert` module provides a set of assertion functions for verifying
* invariants.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/assert.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js)
*/
declare module "assert" {
/**
@@ -45,7 +45,7 @@ declare module "assert" {
/** The `operator` property on the error instance. */
operator?: string | undefined;
/** If provided, the generated stack trace omits frames before this function. */
// eslint-disable-next-line @typescript-eslint/ban-types
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
stackStartFn?: Function | undefined;
});
}
@@ -79,7 +79,9 @@ declare module "assert" {
* @return A function that wraps `fn`.
*/
calls(exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func;
calls(fn: undefined, exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn: Func, exact?: number): Func;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func | (() => void);
/**
* Example:
*
@@ -226,7 +228,7 @@ declare module "assert" {
expected: unknown,
message?: string | Error,
operator?: string,
// eslint-disable-next-line @typescript-eslint/ban-types
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
stackStartFn?: Function,
): never;
/**
@@ -796,7 +798,7 @@ declare module "assert" {
* check that the promise is rejected.
*
* If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the
* function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value)
* function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value)
* error. In both cases the error handler is skipped.
*
* Besides the async nature to await the completion behaves identically to {@link throws}.
@@ -866,7 +868,7 @@ declare module "assert" {
*
* If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If
* the function does not return a promise, `assert.doesNotReject()` will return a
* rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value) error. In both cases
* rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) error. In both cases
* the error handler is skipped.
*
* Using `assert.doesNotReject()` is actually not useful because there is little
@@ -929,7 +931,7 @@ declare module "assert" {
* If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal
* to the value of the `message` parameter. If the `message` parameter is
* undefined, a default error message is assigned. If the `message` parameter is an
* instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* @since v13.6.0, v12.16.0
*/
function match(value: string, regExp: RegExp, message?: string | Error): void;
@@ -952,10 +954,22 @@ declare module "assert" {
* If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal
* to the value of the `message` parameter. If the `message` parameter is
* undefined, a default error message is assigned. If the `message` parameter is an
* instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* @since v13.6.0, v12.16.0
*/
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;
/**
* 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.
*
* 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;
/**
* In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example,
* {@link deepEqual} will behave like {@link deepStrictEqual}.
@@ -966,7 +980,7 @@ declare module "assert" {
* To use strict assertion mode:
*
* ```js
* import { strict as assert } from 'node:assert';COPY
* import { strict as assert } from 'node:assert';
* import assert from 'node:assert/strict';
* ```
*
@@ -1015,6 +1029,7 @@ declare module "assert" {
| "deepStrictEqual"
| "ifError"
| "strict"
| "AssertionError"
>
& {
(value: unknown, message?: string | Error): asserts value;
@@ -1030,6 +1045,7 @@ declare module "assert" {
deepStrictEqual: typeof deepStrictEqual;
ifError: typeof ifError;
strict: typeof strict;
AssertionError: typeof AssertionError;
};
}
export = assert;

View File

@@ -2,8 +2,8 @@
* We strongly discourage the use of the `async_hooks` API.
* Other APIs that can cover most of its use cases include:
*
* * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v22.x/api/async_context.html#class-asynclocalstorage) tracks async context
* * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processgetactiveresourcesinfo) tracks active resources
* * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v24.x/api/async_context.html#class-asynclocalstorage) tracks async context
* * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processgetactiveresourcesinfo) tracks active resources
*
* The `node:async_hooks` module provides an API to track asynchronous resources.
* It can be accessed using:
@@ -12,7 +12,7 @@
* import async_hooks from 'node:async_hooks';
* ```
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/async_hooks.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/async_hooks.js)
*/
declare module "async_hooks" {
/**
@@ -44,7 +44,7 @@ declare module "async_hooks" {
* ```
*
* Promise contexts may not get precise `executionAsyncIds` by default.
* See the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking).
* See the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking).
* @since v8.1.0
* @return The `asyncId` of the current execution context. Useful to track when something calls.
*/
@@ -77,7 +77,7 @@ declare module "async_hooks" {
* executionAsyncId,
* executionAsyncResource,
* createHook,
* } from 'async_hooks';
* } from 'node:async_hooks';
* const sym = Symbol('state'); // Private symbol to avoid pollution
*
* createHook({
@@ -117,7 +117,7 @@ declare module "async_hooks" {
* ```
*
* Promise contexts may not get valid `triggerAsyncId`s by default. See
* the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking).
* the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking).
* @return The ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
@@ -320,6 +320,16 @@ declare module "async_hooks" {
*/
triggerAsyncId(): number;
}
interface AsyncLocalStorageOptions {
/**
* The default value to be used when no store is provided.
*/
defaultValue?: any;
/**
* A name for the `AsyncLocalStorage` value.
*/
name?: string | undefined;
}
/**
* This class creates stores that stay coherent through asynchronous operations.
*
@@ -358,8 +368,8 @@ declare module "async_hooks" {
* http.get('http://localhost:8080');
* // Prints:
* // 0: start
* // 1: start
* // 0: finish
* // 1: start
* // 1: finish
* ```
*
@@ -369,10 +379,14 @@ declare module "async_hooks" {
* @since v13.10.0, v12.17.0
*/
class AsyncLocalStorage<T> {
/**
* Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
* `run()` call or after an `enterWith()` call.
*/
constructor(options?: AsyncLocalStorageOptions);
/**
* 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 +417,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(): <R, TArgs extends any[]>(fn: (...args: TArgs) => R, ...args: TArgs) => R;
@@ -432,6 +445,11 @@ declare module "async_hooks" {
* @since v13.10.0, v12.17.0
*/
getStore(): T | undefined;
/**
* The name of the `AsyncLocalStorage` instance if provided.
* @since v24.0.0
*/
readonly name: string;
/**
* Runs a function synchronously within a context and returns its
* return value. The store is not accessible outside of the callback function.
@@ -535,6 +553,70 @@ declare module "async_hooks" {
*/
enterWith(store: T): void;
}
/**
* @since v17.2.0, v16.14.0
* @return A map of provider types to the corresponding numeric id.
* This map contains all the event types that might be emitted by the `async_hooks.init()` event.
*/
namespace asyncWrapProviders {
const NONE: number;
const DIRHANDLE: number;
const DNSCHANNEL: number;
const ELDHISTOGRAM: number;
const FILEHANDLE: number;
const FILEHANDLECLOSEREQ: number;
const FIXEDSIZEBLOBCOPY: number;
const FSEVENTWRAP: number;
const FSREQCALLBACK: number;
const FSREQPROMISE: number;
const GETADDRINFOREQWRAP: number;
const GETNAMEINFOREQWRAP: number;
const HEAPSNAPSHOT: number;
const HTTP2SESSION: number;
const HTTP2STREAM: number;
const HTTP2PING: number;
const HTTP2SETTINGS: number;
const HTTPINCOMINGMESSAGE: number;
const HTTPCLIENTREQUEST: number;
const JSSTREAM: number;
const JSUDPWRAP: number;
const MESSAGEPORT: number;
const PIPECONNECTWRAP: number;
const PIPESERVERWRAP: number;
const PIPEWRAP: number;
const PROCESSWRAP: number;
const PROMISE: number;
const QUERYWRAP: number;
const SHUTDOWNWRAP: number;
const SIGNALWRAP: number;
const STATWATCHER: number;
const STREAMPIPE: number;
const TCPCONNECTWRAP: number;
const TCPSERVERWRAP: number;
const TCPWRAP: number;
const TTYWRAP: number;
const UDPSENDWRAP: number;
const UDPWRAP: number;
const SIGINTWATCHDOG: number;
const WORKER: number;
const WORKERHEAPSNAPSHOT: number;
const WRITEWRAP: number;
const ZLIB: number;
const CHECKPRIMEREQUEST: number;
const PBKDF2REQUEST: number;
const KEYPAIRGENREQUEST: number;
const KEYGENREQUEST: number;
const KEYEXPORTREQUEST: number;
const CIPHERREQUEST: number;
const DERIVEBITSREQUEST: number;
const HASHREQUEST: number;
const RANDOMBYTESREQUEST: number;
const RANDOMPRIMEREQUEST: number;
const SCRYPTREQUEST: number;
const SIGNREQUEST: number;
const TLSWRAP: number;
const VERIFYREQUEST: number;
}
}
declare module "node:async_hooks" {
export * from "async_hooks";

417
node_modules/@types/node/buffer.d.ts generated vendored
View File

@@ -46,7 +46,7 @@ type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : impo
* // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
* const buf7 = Buffer.from('tést', 'latin1');
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/buffer.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/buffer.js)
*/
declare module "buffer" {
import { BinaryLike } from "node:crypto";
@@ -69,7 +69,7 @@ declare module "buffer" {
* @param input The input to validate.
*/
export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean;
export const INSPECT_MAX_BYTES: number;
export let INSPECT_MAX_BYTES: number;
export const kMaxLength: number;
export const kStringMaxLength: number;
export const constants: {
@@ -114,27 +114,21 @@ declare module "buffer" {
* @param toEnc To target encoding.
*/
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer;
export const SlowBuffer: {
/** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */
new(size: number): Buffer;
prototype: Buffer;
};
/**
* Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using
* a prior call to `URL.createObjectURL()`.
* @since v16.7.0
* @experimental
* @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`.
*/
export function resolveObjectURL(id: string): Blob | undefined;
export { Buffer };
export { type AllowSharedBuffer, Buffer, type NonSharedBuffer };
/**
* @experimental
*/
export interface BlobOptions {
/**
* One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts
* will be converted to the platform native line-ending as specified by `require('node:os').EOL`.
* will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`.
*/
endings?: "transparent" | "native";
/**
@@ -210,7 +204,7 @@ declare module "buffer" {
export interface FileOptions {
/**
* One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be
* converted to the platform native line-ending as specified by `require('node:os').EOL`.
* converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`.
*/
endings?: "native" | "transparent";
/** The File content-type. */
@@ -237,7 +231,10 @@ declare module "buffer" {
}
export import atob = globalThis.atob;
export import btoa = globalThis.btoa;
export type WithImplicitCoercion<T> =
| T
| { valueOf(): T }
| (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never);
global {
namespace NodeJS {
export { BufferEncoding };
@@ -256,111 +253,15 @@ declare module "buffer" {
| "latin1"
| "binary"
| "hex";
type WithImplicitCoercion<T> =
| T
| {
valueOf(): T;
};
/**
* Raw data is stored in instances of the Buffer class.
* A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
* Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex'
*/
interface BufferConstructor {
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
*/
new(str: string, encoding?: BufferEncoding): Buffer;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
*/
new(size: number): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: Uint8Array): Buffer;
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}/{SharedArrayBuffer}.
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
*/
new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: readonly any[]): Buffer;
/**
* Copies the passed {buffer} data onto a new {Buffer} instance.
*
* @param buffer The buffer to copy.
* @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead.
*/
new(buffer: Buffer): Buffer;
/**
* Allocates a new `Buffer` using an `array` of bytes in the range `0` `255`.
* Array entries outside that range will be truncated to fit into it.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
* ```
*
* If `array` is an `Array`\-like object (that is, one with a `length` property of
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`.
*
* A `TypeError` will be thrown if `array` is not an `Array` or another type
* appropriate for `Buffer.from()` variants.
*
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v5.10.0
*/
from(
arrayBuffer: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>,
byteOffset?: number,
length?: number,
): Buffer;
/**
* Creates a new Buffer using the passed {data}
* @param data data to create a new Buffer
*/
from(data: Uint8Array | readonly number[]): Buffer;
from(data: WithImplicitCoercion<Uint8Array | readonly number[] | string>): Buffer;
/**
* Creates a new Buffer containing the given JavaScript string {str}.
* If provided, the {encoding} parameter identifies the character encoding.
* If not provided, {encoding} defaults to 'utf8'.
*/
from(
str:
| WithImplicitCoercion<string>
| {
[Symbol.toPrimitive](hint: "string"): string;
},
encoding?: BufferEncoding,
): Buffer;
/**
* Creates a new Buffer using the passed {data}
* @param values to create a new Buffer
*/
of(...items: number[]): Buffer;
// see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later
// see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier
/**
* Returns `true` if `obj` is a `Buffer`, `false` otherwise.
*
@@ -432,62 +333,6 @@ declare module "buffer" {
string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
encoding?: BufferEncoding,
): number;
/**
* Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together.
*
* If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned.
*
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
* in `list` by adding their lengths.
*
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
* truncated to `totalLength`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a single `Buffer` from a list of three `Buffer` instances.
*
* const buf1 = Buffer.alloc(10);
* const buf2 = Buffer.alloc(14);
* const buf3 = Buffer.alloc(18);
* const totalLength = buf1.length + buf2.length + buf3.length;
*
* console.log(totalLength);
* // Prints: 42
*
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
*
* console.log(bufA);
* // Prints: <Buffer 00 00 00 00 ...>
* console.log(bufA.length);
* // Prints: 42
* ```
*
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v0.7.11
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
*/
concat(list: readonly Uint8Array[], totalLength?: number): Buffer;
/**
* Copies the underlying memory of `view` into a new `Buffer`.
*
* ```js
* const u16 = new Uint16Array([0, 0xffff]);
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
* u16[1] = 0;
* console.log(buf.length); // 2
* console.log(buf[0]); // 255
* console.log(buf[1]); // 255
* ```
* @since v19.8.0
* @param view The {TypedArray} to copy.
* @param [offset=0] The starting offset within `view`.
* @param [length=view.length - offset] The number of elements from `view` to copy.
*/
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer;
/**
* Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`.
*
@@ -506,135 +351,6 @@ declare module "buffer" {
* @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details.
*/
compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1;
/**
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00>
* ```
*
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
*
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5, 'a');
*
* console.log(buf);
* // Prints: <Buffer 61 61 61 61 61>
* ```
*
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
* initialized by calling `buf.fill(fill, encoding)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
*
* console.log(buf);
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
* ```
*
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
* contents will never contain sensitive data from previous allocations, including
* data that might not have been allocated for `Buffer`s.
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
* @param [fill=0] A value to pre-fill the new `Buffer` with.
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
*/
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(10);
*
* console.log(buf);
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
*
* buf.fill(0);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
*
* The `Buffer` module pre-allocates an internal `Buffer` instance of
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
* and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
*
* Use of this pre-allocated internal memory pool is a key difference between
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
* than or equal to half `Buffer.poolSize`. The
* difference is subtle but can be important when an application requires the
* additional performance that `Buffer.allocUnsafe()` provides.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafe(size: number): Buffer;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if
* `size` is 0.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize
* 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.
*
* 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
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
* then copying out the relevant bits.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Need to keep around a few small chunks of memory.
* const store = [];
*
* socket.on('readable', () => {
* let data;
* while (null !== (data = readable.read())) {
* // Allocate for retained data.
* const sb = Buffer.allocUnsafeSlow(10);
*
* // Copy the data into the new allocation.
* data.copy(sb, 0, 0, 10);
*
* store.push(sb);
* }
* });
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.12.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafeSlow(size: number): Buffer;
/**
* This is the size (in bytes) of pre-allocated internal `Buffer` instances used
* for pooling. This value may be modified.
@@ -642,7 +358,10 @@ declare module "buffer" {
*/
poolSize: number;
}
interface Buffer extends Uint8Array {
interface Buffer {
// see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later
// see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier
/**
* Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did
* not contain enough space to fit the entire string, only part of `string` will be
@@ -879,100 +598,6 @@ declare module "buffer" {
* @return The number of bytes copied.
*/
copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* This method is not compatible with the `Uint8Array.prototype.slice()`,
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
* copiedBuf[0]++;
* console.log(copiedBuf.toString());
* // Prints: cuffer
*
* console.log(buf.toString());
* // Prints: buffer
*
* // With buf.slice(), the original buffer is modified.
* const notReallyCopiedBuf = buf.slice();
* notReallyCopiedBuf[0]++;
* console.log(notReallyCopiedBuf.toString());
* // Prints: cuffer
* console.log(buf.toString());
* // Also prints: cuffer (!)
* ```
* @since v0.3.0
* @deprecated Use `subarray` instead.
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
*/
slice(start?: number, end?: number): Buffer;
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* Specifying `end` greater than `buf.length` will return the same result as
* that of `end` equal to `buf.length`.
*
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
*
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
* // from the original `Buffer`.
*
* const buf1 = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* const buf2 = buf1.subarray(0, 3);
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: abc
*
* buf1[0] = 33;
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: !bc
* ```
*
* Specifying negative indexes causes the slice to be generated relative to the
* end of `buf` rather than the beginning.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* console.log(buf.subarray(-6, -1).toString());
* // Prints: buffe
* // (Equivalent to buf.subarray(0, 5).)
*
* console.log(buf.subarray(-6, -2).toString());
* // Prints: buff
* // (Equivalent to buf.subarray(0, 4).)
*
* console.log(buf.subarray(-5, -2).toString());
* // Prints: uff
* // (Equivalent to buf.subarray(1, 4).)
* ```
* @since v3.0.0
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
*/
subarray(start?: number, end?: number): Buffer;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian.
*
@@ -1630,7 +1255,7 @@ declare module "buffer" {
* @since v5.10.0
* @return A reference to `buf`.
*/
swap16(): Buffer;
swap16(): this;
/**
* Interprets `buf` as an array of unsigned 32-bit integers and swaps the
* byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4.
@@ -1656,7 +1281,7 @@ declare module "buffer" {
* @since v5.10.0
* @return A reference to `buf`.
*/
swap32(): Buffer;
swap32(): this;
/**
* Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_.
* Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8.
@@ -1682,7 +1307,7 @@ declare module "buffer" {
* @since v6.3.0
* @return A reference to `buf`.
*/
swap64(): Buffer;
swap64(): this;
/**
* Writes `value` to `buf` at the specified `offset`. `value` must be a
* valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
@@ -2279,7 +1904,7 @@ declare module "buffer" {
function btoa(data: string): string;
interface Blob extends _Blob {}
/**
* `Blob` class is a global reference for `require('node:buffer').Blob`
* `Blob` class is a global reference for `import { Blob } from 'node:buffer'`
* https://nodejs.org/api/buffer.html#class-blob
* @since v18.0.0
*/
@@ -2287,7 +1912,7 @@ declare module "buffer" {
: typeof import("buffer").Blob;
interface File extends _File {}
/**
* `File` class is a global reference for `require('node:buffer').File`
* `File` class is a global reference for `import { File } from 'node:buffer'`
* https://nodejs.org/api/buffer.html#class-file
* @since v20.0.0
*/

View File

@@ -4,7 +4,7 @@
* is primarily provided by the {@link spawn} function:
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const ls = spawn('ls', ['-lh', '/usr']);
*
* ls.stdout.on('data', (data) => {
@@ -63,7 +63,7 @@
* For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however,
* the synchronous methods can have significant impact on performance due to
* stalling the event loop while spawned processes complete.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/child_process.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js)
*/
declare module "child_process" {
import { ObjectEncodingOptions } from "node:fs";
@@ -109,7 +109,7 @@ declare module "child_process" {
* refer to the same value.
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
*
* const subprocess = spawn('ls');
*
@@ -152,9 +152,9 @@ declare module "child_process" {
* in the array are `null`.
*
* ```js
* const assert = require('node:assert');
* const fs = require('node:fs');
* const child_process = require('node:child_process');
* import assert from 'node:assert';
* import fs from 'node:fs';
* import child_process from 'node:child_process';
*
* const subprocess = child_process.spawn('ls', {
* stdio: [
@@ -202,7 +202,7 @@ declare module "child_process" {
* emitted.
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const grep = spawn('grep', ['ssh']);
*
* console.log(`Spawned child pid: ${grep.pid}`);
@@ -249,7 +249,7 @@ declare module "child_process" {
* returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise.
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const grep = spawn('grep', ['ssh']);
*
* grep.on('close', (code, signal) => {
@@ -282,7 +282,7 @@ declare module "child_process" {
*
* ```js
* 'use strict';
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
*
* const subprocess = spawn(
* 'sh',
@@ -320,7 +320,7 @@ declare module "child_process" {
* For example, in the parent script:
*
* ```js
* const cp = require('node:child_process');
* import cp from 'node:child_process';
* const n = cp.fork(`${__dirname}/sub.js`);
*
* n.on('message', (m) => {
@@ -374,10 +374,12 @@ declare module "child_process" {
* a TCP server object to the child process as illustrated in the example below:
*
* ```js
* const subprocess = require('node:child_process').fork('subprocess.js');
* import { createServer } from 'node:net';
* import { fork } from 'node:child_process';
* const subprocess = fork('subprocess.js');
*
* // Open up the server object and send the handle.
* const server = require('node:net').createServer();
* const server = createServer();
* server.on('connection', (socket) => {
* socket.end('handled by parent');
* });
@@ -412,13 +414,14 @@ declare module "child_process" {
* handle connections with "normal" or "special" priority:
*
* ```js
* const { fork } = require('node:child_process');
* import { createServer } from 'node:net';
* import { fork } from 'node:child_process';
* const normal = fork('subprocess.js', ['normal']);
* const special = fork('subprocess.js', ['special']);
*
* // Open up the server and send sockets to child. Use pauseOnConnect to prevent
* // the sockets from being read before they are sent to the child process.
* const server = require('node:net').createServer({ pauseOnConnect: true });
* const server = createServer({ pauseOnConnect: true });
* server.on('connection', (socket) => {
*
* // If this is special priority...
@@ -455,7 +458,7 @@ declare module "child_process" {
* as the connection may have been closed during the time it takes to send the
* connection to the child.
* @since v0.5.9
* @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v22.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v22.x/api/dgram.html#class-dgramsocket) object.
* @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v24.x/api/dgram.html#class-dgramsocket) object.
* @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:
*/
send(message: Serializable, callback?: (error: Error | null) => void): boolean;
@@ -490,7 +493,7 @@ declare module "child_process" {
* the child and the parent.
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
*
* const subprocess = spawn(process.argv[0], ['child_program.js'], {
* detached: true,
@@ -508,7 +511,7 @@ declare module "child_process" {
* to wait for the child to exit before exiting itself.
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
*
* const subprocess = spawn(process.argv[0], ['child_program.js'], {
* detached: true,
@@ -711,7 +714,7 @@ declare module "child_process" {
* exit code:
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const ls = spawn('ls', ['-lh', '/usr']);
*
* ls.stdout.on('data', (data) => {
@@ -730,7 +733,7 @@ declare module "child_process" {
* Example: A very elaborate way to run `ps ax | grep ssh`
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const ps = spawn('ps', ['ax']);
* const grep = spawn('grep', ['ssh']);
*
@@ -767,7 +770,7 @@ declare module "child_process" {
* Example of checking for failed `spawn`:
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const subprocess = spawn('bad_command');
*
* subprocess.on('error', (err) => {
@@ -785,7 +788,7 @@ declare module "child_process" {
* the error passed to the callback will be an `AbortError`:
*
* ```js
* const { spawn } = require('node:child_process');
* import { spawn } from 'node:child_process';
* const controller = new AbortController();
* const { signal } = controller;
* const grep = spawn('grep', ['ssh'], { signal });
@@ -906,7 +909,7 @@ declare module "child_process" {
* need to be dealt with accordingly:
*
* ```js
* const { exec } = require('node:child_process');
* import { exec } from 'node:child_process';
*
* exec('"/path/to/test file/test.sh" arg1 arg2');
* // Double quotes are used so that the space in the path is not interpreted as
@@ -932,7 +935,7 @@ declare module "child_process" {
* encoding, `Buffer` objects will be passed to the callback instead.
*
* ```js
* const { exec } = require('node:child_process');
* import { exec } from 'node:child_process';
* exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
* if (error) {
* console.error(`exec error: ${error}`);
@@ -957,8 +960,9 @@ declare module "child_process" {
* callback, but with two additional properties `stdout` and `stderr`.
*
* ```js
* const util = require('node:util');
* const exec = util.promisify(require('node:child_process').exec);
* import util from 'node:util';
* import child_process from 'node:child_process';
* const exec = util.promisify(child_process.exec);
*
* async function lsExample() {
* const { stdout, stderr } = await exec('ls');
@@ -972,7 +976,7 @@ declare module "child_process" {
* the error passed to the callback will be an `AbortError`:
*
* ```js
* const { exec } = require('node:child_process');
* import { exec } from 'node:child_process';
* const controller = new AbortController();
* const { signal } = controller;
* const child = exec('grep ssh', { signal }, (error) => {
@@ -1096,7 +1100,7 @@ declare module "child_process" {
* supported.
*
* ```js
* const { execFile } = require('node:child_process');
* import { execFile } from 'node:child_process';
* const child = execFile('node', ['--version'], (error, stdout, stderr) => {
* if (error) {
* throw error;
@@ -1119,8 +1123,9 @@ declare module "child_process" {
* callback, but with two additional properties `stdout` and `stderr`.
*
* ```js
* const util = require('node:util');
* const execFile = util.promisify(require('node:child_process').execFile);
* import util from 'node:util';
* import child_process from 'node:child_process';
* const execFile = util.promisify(child_process.execFile);
* async function getVersion() {
* const { stdout } = await execFile('node', ['--version']);
* console.log(stdout);
@@ -1136,7 +1141,7 @@ declare module "child_process" {
* the error passed to the callback will be an `AbortError`:
*
* ```js
* const { execFile } = require('node:child_process');
* import { execFile } from 'node:child_process';
* const controller = new AbortController();
* const { signal } = controller;
* const child = execFile('node', ['--version'], { signal }, (error) => {
@@ -1377,7 +1382,7 @@ declare module "child_process" {
* console.log(`Hello from ${process.argv[2]}!`);
* }, 1_000);
* } else {
* const { fork } = require('node:child_process');
* import { fork } from 'node:child_process';
* const controller = new AbortController();
* const { signal } = controller;
* const child = fork(__filename, ['child'], { signal });

View File

@@ -1,7 +1,7 @@
/**
* Clusters of Node.js processes can be used to run multiple instances of Node.js
* that can distribute workloads among their application threads. When process isolation
* is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html)
* is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html)
* module instead, which allows running multiple application threads within a single Node.js instance.
*
* The cluster module allows easy creation of child processes that all share
@@ -50,7 +50,7 @@
* ```
*
* On Windows, it is not yet possible to set up a named pipe server in a worker.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/cluster.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/cluster.js)
*/
declare module "cluster" {
import * as child from "node:child_process";
@@ -80,8 +80,8 @@ declare module "cluster" {
silent?: boolean | undefined;
/**
* Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must
* contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processspawncommand-args-options)'s
* [`stdio`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#optionsstdio).
* contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processspawncommand-args-options)'s
* [`stdio`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#optionsstdio).
*/
stdio?: any[] | undefined;
/**
@@ -99,7 +99,7 @@ declare module "cluster" {
inspectPort?: number | (() => number) | undefined;
/**
* Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`.
* See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#advanced-serialization) for more details.
* See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#advanced-serialization) for more details.
* @default false
*/
serialization?: SerializationType | undefined;
@@ -142,10 +142,10 @@ declare module "cluster" {
*/
id: number;
/**
* All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object
* All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object
* from this function is stored as `.process`. In a worker, the global `process` is stored.
*
* See: [Child Process module](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options).
* See: [Child Process module](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options).
*
* Workers will call `process.exit(0)` if the `'disconnect'` event occurs
* on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
@@ -156,7 +156,7 @@ declare module "cluster" {
/**
* Send a message to a worker or primary, optionally with a handle.
*
* In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback).
* In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback).
*
* In a worker, this sends a message to the primary. It is identical to `process.send()`.
*
@@ -198,7 +198,7 @@ declare module "cluster" {
* This method is aliased as `worker.destroy()` for backwards compatibility.
*
* In a worker, `process.kill()` exists, but it is not this function;
* it is [`kill()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processkillpid-signal).
* it is [`kill()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processkillpid-signal).
* @since v0.9.12
* @param [signal='SIGTERM'] Name of the kill signal to send to the worker process.
*/
@@ -231,6 +231,8 @@ declare module "cluster" {
* the `'disconnect'` event has not been emitted after some time.
*
* ```js
* import net from 'node:net';
*
* if (cluster.isPrimary) {
* const worker = cluster.fork();
* let timeout;
@@ -248,7 +250,6 @@ declare module "cluster" {
* });
*
* } else if (cluster.isWorker) {
* const net = require('node:net');
* const server = net.createServer((socket) => {
* // Connections never end
* });
@@ -265,7 +266,7 @@ declare module "cluster" {
* @since v0.7.7
* @return A reference to `worker`.
*/
disconnect(): void;
disconnect(): this;
/**
* This function returns `true` if the worker is connected to its primary via its
* IPC channel, `false` otherwise. A worker is connected to its primary after it
@@ -411,7 +412,7 @@ declare module "cluster" {
readonly isWorker: boolean;
/**
* The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a
* global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings)
* global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings)
* is called, whichever comes first.
*
* `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute
@@ -422,24 +423,24 @@ declare module "cluster" {
*/
schedulingPolicy: number;
/**
* After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings)
* (or [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv)) this settings object will contain
* After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings)
* (or [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)) this settings object will contain
* the settings, including the default values.
*
* This object is not intended to be changed or set manually.
* @since v0.7.1
*/
readonly settings: ClusterSettings;
/** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) instead. */
/** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) instead. */
setupMaster(settings?: ClusterSettings): void;
/**
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`.
*
* Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv)
* Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)
* and have no effect on workers that are already running.
*
* The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to
* [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv).
* [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv).
*
* The defaults above apply to the first call only; the defaults for later calls are the current values at the time of
* `cluster.setupPrimary()` is called.

View File

@@ -5,12 +5,12 @@
* The module exports two specific components:
*
* * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream.
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
* [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without calling `require('node:console')`.
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and
* [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
*
* _**Warning**_: The global console object's methods are neither consistently
* synchronous like the browser APIs they resemble, nor are they consistently
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for
* more information.
*
* Example using the global `console`:
@@ -54,7 +54,7 @@
* myConsole.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to err
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
*/
declare module "console" {
import console = require("node:console");
@@ -70,7 +70,7 @@ declare module "node:console" {
* `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
* writes a message and does not otherwise affect execution. The output always
* starts with `"Assertion failed"`. If provided, `message` is formatted using
* [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args).
* [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args).
*
* If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
*
@@ -152,7 +152,7 @@ declare module "node:console" {
*/
debug(message?: any, ...optionalParams: any[]): void;
/**
* Uses [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`.
* Uses [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`.
* This function bypasses any custom `inspect()` function defined on `obj`.
* @since v0.1.101
*/
@@ -167,7 +167,7 @@ declare module "node:console" {
* Prints to `stderr` with newline. Multiple arguments can be passed, with the
* first used as the primary message and all additional used as substitution
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)).
*
* ```js
* const code = 5;
@@ -178,8 +178,8 @@ declare module "node:console" {
* ```
*
* If formatting elements (e.g. `%d`) are not found in the first string then
* [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
* resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
* [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the
* resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)
* for more information.
* @since v0.1.100
*/
@@ -211,7 +211,7 @@ declare module "node:console" {
* Prints to `stdout` with newline. Multiple arguments can be passed, with the
* first used as the primary message and all additional used as substitution
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)).
*
* ```js
* const count = 5;
@@ -221,7 +221,7 @@ declare module "node:console" {
* // Prints: count: 5, to stdout
* ```
*
* See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
* See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
* @since v0.1.100
*/
log(message?: any, ...optionalParams: any[]): void;
@@ -297,7 +297,7 @@ declare module "node:console" {
*/
timeLog(label?: string, ...data: any[]): void;
/**
* Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
* Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)
* formatted message and stack trace to the current position in the code.
*
* ```js
@@ -361,12 +361,12 @@ declare module "node:console" {
* The module exports two specific components:
*
* * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
* [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`.
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and
* [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
*
* _**Warning**_: The global console object's methods are neither consistently
* synchronous like the browser APIs they resemble, nor are they consistently
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for
* more information.
*
* Example using the global `console`:
@@ -410,7 +410,7 @@ declare module "node:console" {
* myConsole.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to err
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
*/
namespace console {
interface ConsoleConstructorOptions {
@@ -431,7 +431,7 @@ declare module "node:console" {
colorMode?: boolean | "auto" | undefined;
/**
* Specifies options that are passed along to
* [`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options).
* [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options).
*/
inspectOptions?: InspectOptions | undefined;
/**

View File

@@ -1,16 +1,18 @@
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
/**
* @deprecated The `node:constants` module is deprecated. When requiring access to constants
* relevant to specific Node.js builtin modules, developers should instead refer
* to the `constants` property exposed by the relevant module. For instance,
* `require('node:fs').constants` and `require('node:os').constants`.
*/
declare module "constants" {
import { constants as osConstants, SignalConstants } from "node:os";
import { constants as cryptoConstants } from "node:crypto";
import { constants as fsConstants } from "node:fs";
const exp:
& typeof osConstants.errno
& typeof osConstants.priority
& SignalConstants
& typeof cryptoConstants
& typeof fsConstants;
export = exp;
const constants:
& typeof import("node:os").constants.dlopen
& typeof import("node:os").constants.errno
& typeof import("node:os").constants.priority
& typeof import("node:os").constants.signals
& typeof import("node:fs").constants
& typeof import("node:crypto").constants;
export = constants;
}
declare module "node:constants" {

161
node_modules/@types/node/crypto.d.ts generated vendored
View File

@@ -14,7 +14,7 @@
* // Prints:
* // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/crypto.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/crypto.js)
*/
declare module "crypto" {
import * as stream from "node:stream";
@@ -96,7 +96,7 @@ declare module "crypto" {
verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
}
namespace constants {
// https://nodejs.org/dist/latest-v22.x/docs/api/crypto.html#crypto-constants
// https://nodejs.org/dist/latest-v24.x/docs/api/crypto.html#crypto-constants
const OPENSSL_VERSION_NUMBER: number;
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
const SSL_OP_ALL: number;
@@ -609,11 +609,6 @@ declare module "crypto" {
* @since v11.6.0
*/
asymmetricKeyType?: KeyType | undefined;
/**
* For asymmetric keys, this property represents the size of the embedded key in
* bytes. This property is `undefined` for symmetric keys.
*/
asymmetricKeySize?: number | undefined;
/**
* This property exists only on asymmetric keys. Depending on the type of the key,
* this object contains information about the key. None of the information obtained
@@ -667,6 +662,19 @@ declare module "crypto" {
* @since v11.6.0
*/
symmetricKeySize?: number | undefined;
/**
* Converts a `KeyObject` instance to a `CryptoKey`.
* @since 22.10.0
*/
toCryptoKey(
algorithm:
| webcrypto.AlgorithmIdentifier
| webcrypto.RsaHashedImportParams
| webcrypto.EcKeyImportParams
| webcrypto.HmacImportParams,
extractable: boolean,
keyUsages: readonly webcrypto.KeyUsage[],
): webcrypto.CryptoKey;
/**
* Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
* or `'private'` for private (asymmetric) keys.
@@ -674,9 +682,10 @@ declare module "crypto" {
*/
type: KeyObjectType;
}
type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305";
type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm";
type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb";
type CipherChaCha20Poly1305Types = "chacha20-poly1305";
type BinaryLike = string | NodeJS.ArrayBufferView;
type CipherKey = BinaryLike | KeyObject;
interface CipherCCMOptions extends stream.TransformOptions {
@@ -688,6 +697,10 @@ declare module "crypto" {
interface CipherOCBOptions extends stream.TransformOptions {
authTagLength: number;
}
interface CipherChaCha20Poly1305Options extends stream.TransformOptions {
/** @default 16 */
authTagLength?: number | undefined;
}
/**
* Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
* initialization vector (`iv`).
@@ -736,14 +749,20 @@ declare module "crypto" {
iv: BinaryLike,
options?: CipherGCMOptions,
): CipherGCM;
function createCipheriv(
algorithm: CipherChaCha20Poly1305Types,
key: CipherKey,
iv: BinaryLike,
options?: CipherChaCha20Poly1305Options,
): CipherChaCha20Poly1305;
function createCipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions,
): Cipher;
): Cipheriv;
/**
* Instances of the `Cipher` class are used to encrypt data. The class can be
* Instances of the `Cipheriv` class are used to encrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain unencrypted
@@ -752,10 +771,10 @@ declare module "crypto" {
* the encrypted data.
*
* The {@link createCipheriv} method is
* used to create `Cipher` instances. `Cipher` objects are not to be created
* used to create `Cipheriv` instances. `Cipheriv` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Cipher` objects as streams:
* Example: Using `Cipheriv` objects as streams:
*
* ```js
* const {
@@ -790,7 +809,7 @@ declare module "crypto" {
* });
* ```
*
* Example: Using `Cipher` and piped streams:
* Example: Using `Cipheriv` and piped streams:
*
* ```js
* import {
@@ -861,7 +880,7 @@ declare module "crypto" {
* ```
* @since v0.1.94
*/
class Cipher extends stream.Transform {
class Cipheriv extends stream.Transform {
private constructor();
/**
* Updates the cipher with `data`. If the `inputEncoding` argument is given,
@@ -882,7 +901,7 @@ declare module "crypto" {
update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
/**
* Once the `cipher.final()` method has been called, the `Cipher` object can no
* Once the `cipher.final()` method has been called, the `Cipheriv` object can no
* longer be used to encrypt data. Attempts to call `cipher.final()` more than
* once will result in an error being thrown.
* @since v0.1.94
@@ -892,7 +911,7 @@ declare module "crypto" {
final(): Buffer;
final(outputEncoding: BufferEncoding): string;
/**
* When using block encryption algorithms, the `Cipher` class will automatically
* When using block encryption algorithms, the `Cipheriv` class will automatically
* add padding to the input data to the appropriate block size. To disable the
* default padding call `cipher.setAutoPadding(false)`.
*
@@ -908,7 +927,7 @@ declare module "crypto" {
*/
setAutoPadding(autoPadding?: boolean): this;
}
interface CipherCCM extends Cipher {
interface CipherCCM extends Cipheriv {
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
@@ -917,7 +936,7 @@ declare module "crypto" {
): this;
getAuthTag(): Buffer;
}
interface CipherGCM extends Cipher {
interface CipherGCM extends Cipheriv {
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
@@ -926,7 +945,7 @@ declare module "crypto" {
): this;
getAuthTag(): Buffer;
}
interface CipherOCB extends Cipher {
interface CipherOCB extends Cipheriv {
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
@@ -935,8 +954,17 @@ declare module "crypto" {
): this;
getAuthTag(): Buffer;
}
interface CipherChaCha20Poly1305 extends Cipheriv {
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
plaintextLength: number;
},
): this;
getAuthTag(): Buffer;
}
/**
* Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`).
* Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the
@@ -982,14 +1010,20 @@ declare module "crypto" {
iv: BinaryLike,
options?: CipherGCMOptions,
): DecipherGCM;
function createDecipheriv(
algorithm: CipherChaCha20Poly1305Types,
key: CipherKey,
iv: BinaryLike,
options?: CipherChaCha20Poly1305Options,
): DecipherChaCha20Poly1305;
function createDecipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions,
): Decipher;
): Decipheriv;
/**
* Instances of the `Decipher` class are used to decrypt data. The class can be
* Instances of the `Decipheriv` class are used to decrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain encrypted
@@ -998,10 +1032,10 @@ declare module "crypto" {
* produce the unencrypted data.
*
* The {@link createDecipheriv} method is
* used to create `Decipher` instances. `Decipher` objects are not to be created
* used to create `Decipheriv` instances. `Decipheriv` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Decipher` objects as streams:
* Example: Using `Decipheriv` objects as streams:
*
* ```js
* import { Buffer } from 'node:buffer';
@@ -1040,7 +1074,7 @@ declare module "crypto" {
* decipher.end();
* ```
*
* Example: Using `Decipher` and piped streams:
* Example: Using `Decipheriv` and piped streams:
*
* ```js
* import {
@@ -1096,7 +1130,7 @@ declare module "crypto" {
* ```
* @since v0.1.94
*/
class Decipher extends stream.Transform {
class Decipheriv extends stream.Transform {
private constructor();
/**
* Updates the decipher with `data`. If the `inputEncoding` argument is given,
@@ -1117,7 +1151,7 @@ declare module "crypto" {
update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
/**
* Once the `decipher.final()` method has been called, the `Decipher` object can
* Once the `decipher.final()` method has been called, the `Decipheriv` object can
* no longer be used to decrypt data. Attempts to call `decipher.final()` more
* than once will result in an error being thrown.
* @since v0.1.94
@@ -1140,7 +1174,7 @@ declare module "crypto" {
*/
setAutoPadding(auto_padding?: boolean): this;
}
interface DecipherCCM extends Decipher {
interface DecipherCCM extends Decipheriv {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
@@ -1149,7 +1183,7 @@ declare module "crypto" {
},
): this;
}
interface DecipherGCM extends Decipher {
interface DecipherGCM extends Decipheriv {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
@@ -1158,7 +1192,7 @@ declare module "crypto" {
},
): this;
}
interface DecipherOCB extends Decipher {
interface DecipherOCB extends Decipheriv {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
@@ -1167,6 +1201,15 @@ declare module "crypto" {
},
): this;
}
interface DecipherChaCha20Poly1305 extends Decipheriv {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
plaintextLength: number;
},
): this;
}
interface PrivateKeyInput {
key: string | Buffer;
format?: KeyFormat | undefined;
@@ -2139,7 +2182,10 @@ declare module "crypto" {
* be passed instead of a public key.
* @since v0.11.14
*/
function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function publicEncrypt(
key: RsaPublicKey | RsaPrivateKey | KeyLike,
buffer: NodeJS.ArrayBufferView | string,
): Buffer;
/**
* Decrypts `buffer` with `key`.`buffer` was previously encrypted using
* the corresponding private key, for example using {@link privateEncrypt}.
@@ -2151,7 +2197,10 @@ declare module "crypto" {
* be passed instead of a public key.
* @since v1.1.0
*/
function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function publicDecrypt(
key: RsaPublicKey | RsaPrivateKey | KeyLike,
buffer: NodeJS.ArrayBufferView | string,
): Buffer;
/**
* Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
* the corresponding public key, for example using {@link publicEncrypt}.
@@ -2160,7 +2209,7 @@ declare module "crypto" {
* object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`.
* @since v0.11.14
*/
function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer;
/**
* Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
* the corresponding public key, for example using {@link publicDecrypt}.
@@ -2169,7 +2218,7 @@ declare module "crypto" {
* object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`.
* @since v1.1.0
*/
function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer;
/**
* ```js
* const {
@@ -3303,10 +3352,17 @@ declare module "crypto" {
): void;
/**
* Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
* Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
* Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
* (for Diffie-Hellman), `'ec'`, `'x448'`, or `'x25519'` (for ECDH).
*
* 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 }): Buffer;
function diffieHellman(
options: { privateKey: KeyObject; publicKey: KeyObject },
callback: (err: Error | null, secret: Buffer) => void,
): void;
/**
* A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data
* (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm`
@@ -3316,8 +3372,8 @@ declare module "crypto" {
* Example:
*
* ```js
* const crypto = require('node:crypto');
* const { Buffer } = require('node:buffer');
* import crypto from 'node:crypto';
* import { Buffer } from 'node:buffer';
*
* // Hashing a string and return the result as a hex-encoded string.
* const string = 'Node.js';
@@ -3333,7 +3389,7 @@ declare module "crypto" {
* @since v21.7.0, v20.12.0
* @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user
* could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead.
* @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v22.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest.
* @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v24.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest.
*/
function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string;
function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer;
@@ -3648,11 +3704,21 @@ declare module "crypto" {
* @since v15.6.0
*/
readonly validFrom: string;
/**
* The date/time from which this certificate is valid, encapsulated in a `Date` object.
* @since v22.10.0
*/
readonly validFromDate: Date;
/**
* The date/time until which this certificate is considered valid.
* @since v15.6.0
*/
readonly validTo: string;
/**
* The date/time until which this certificate is valid, encapsulated in a `Date` object.
* @since v22.10.0
*/
readonly validToDate: Date;
constructor(buffer: BinaryLike);
/**
* Checks whether the certificate matches the given email address.
@@ -4034,7 +4100,7 @@ declare module "crypto" {
saltLength: number;
}
/**
* Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class.
* 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.
* @since v15.0.0
*/
@@ -4162,9 +4228,13 @@ declare module "crypto" {
* - `'PBKDF2'`
* @since v15.0.0
*/
deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise<ArrayBuffer>;
deriveBits(
algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params,
algorithm: EcdhKeyDeriveParams,
baseKey: CryptoKey,
length?: number | null,
): Promise<ArrayBuffer>;
deriveBits(
algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
baseKey: CryptoKey,
length: number,
): Promise<ArrayBuffer>;
@@ -4186,14 +4256,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<CryptoKey>;

19
node_modules/@types/node/dgram.d.ts generated vendored
View File

@@ -23,10 +23,10 @@
* server.bind(41234);
* // Prints: server listening 0.0.0.0:41234
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/dgram.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js)
*/
declare module "dgram" {
import { AddressInfo } from "node:net";
import { AddressInfo, BlockList } from "node:net";
import * as dns from "node:dns";
import { Abortable, EventEmitter } from "node:events";
interface RemoteInfo {
@@ -45,6 +45,7 @@ declare module "dgram" {
interface SocketOptions extends Abortable {
type: SocketType;
reuseAddr?: boolean | undefined;
reusePort?: boolean | undefined;
/**
* @default false
*/
@@ -58,6 +59,8 @@ declare module "dgram" {
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
) => void)
| undefined;
receiveBlockList?: BlockList | undefined;
sendBlockList?: BlockList | undefined;
}
/**
* Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram
@@ -352,22 +355,22 @@ declare module "dgram" {
* @param callback Called when the message has been sent.
*/
send(
msg: string | Uint8Array | readonly any[],
msg: string | NodeJS.ArrayBufferView | readonly any[],
port?: number,
address?: string,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array | readonly any[],
msg: string | NodeJS.ArrayBufferView | readonly any[],
port?: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array | readonly any[],
msg: string | NodeJS.ArrayBufferView | readonly any[],
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array,
msg: string | NodeJS.ArrayBufferView,
offset: number,
length: number,
port?: number,
@@ -375,14 +378,14 @@ declare module "dgram" {
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array,
msg: string | NodeJS.ArrayBufferView,
offset: number,
length: number,
port?: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array,
msg: string | NodeJS.ArrayBufferView,
offset: number,
length: number,
callback?: (error: Error | null, bytes: number) => void,

View File

@@ -20,7 +20,7 @@
* should generally include the module name to avoid collisions with data from
* other modules.
* @since v15.1.0, v14.17.0
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/diagnostics_channel.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/diagnostics_channel.js)
*/
declare module "diagnostics_channel" {
import { AsyncLocalStorage } from "node:async_hooks";
@@ -259,7 +259,7 @@ declare module "diagnostics_channel" {
* @param store The store to unbind from the channel.
* @return `true` if the store was found, `false` otherwise.
*/
unbindStore(store: any): void;
unbindStore(store: AsyncLocalStorage<StoreType>): boolean;
/**
* Applies the given data to any AsyncLocalStorage instances bound to the channel
* for the duration of the given function, then publishes to the channel within
@@ -297,7 +297,12 @@ declare module "diagnostics_channel" {
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runStores(): void;
runStores<ThisArg = any, Args extends any[] = any[], Result = any>(
context: ContextType,
fn: (this: ThisArg, ...args: Args) => Result,
thisArg?: ThisArg,
...args: Args
): Result;
}
interface TracingChannelSubscribers<ContextType extends object> {
start: (message: ContextType) => void;
@@ -441,12 +446,12 @@ declare module "diagnostics_channel" {
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceSync<ThisArg = any, Args extends any[] = any[]>(
fn: (this: ThisArg, ...args: Args) => any,
traceSync<ThisArg = any, Args extends any[] = any[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Result,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
): Result;
/**
* Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also
@@ -476,12 +481,12 @@ declare module "diagnostics_channel" {
* @param args Optional arguments to pass to the function
* @return Chained from promise returned by the given function
*/
tracePromise<ThisArg = any, Args extends any[] = any[]>(
fn: (this: ThisArg, ...args: Args) => Promise<any>,
tracePromise<ThisArg = any, Args extends any[] = any[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Promise<Result>,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
): Promise<Result>;
/**
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
@@ -540,13 +545,32 @@ declare module "diagnostics_channel" {
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceCallback<Fn extends (this: any, ...args: any) => any>(
fn: Fn,
position: number | undefined,
context: ContextType | undefined,
thisArg: any,
...args: Parameters<Fn>
): void;
traceCallback<ThisArg = any, Args extends any[] = any[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Result,
position?: number,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): Result;
/**
* `true` if any of the individual channels has a subscriber, `false` if not.
*
* This is a helper method available on a {@link TracingChannel} instance to check
* if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers.
* A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise.
*
* ```js
* const diagnostics_channel = require('node:diagnostics_channel');
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* if (channels.hasSubscribers) {
* // Do something
* }
* ```
* @since v22.0.0, v20.13.0
*/
readonly hasSubscribers: boolean;
}
}
declare module "node:diagnostics_channel" {

100
node_modules/@types/node/dns.d.ts generated vendored
View File

@@ -9,7 +9,7 @@
* system do, use {@link lookup}.
*
* ```js
* const dns = require('node:dns');
* import dns from 'node:dns';
*
* dns.lookup('example.org', (err, address, family) => {
* console.log('address: %j family: IPv%s', address, family);
@@ -23,7 +23,7 @@
* DNS queries, bypassing other name-resolution facilities.
*
* ```js
* const dns = require('node:dns');
* import dns from 'node:dns';
*
* dns.resolve4('archive.org', (err, addresses) => {
* if (err) throw err;
@@ -41,8 +41,8 @@
* });
* ```
*
* See the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations) for more information.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/dns.js)
* See the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) for more information.
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dns.js)
*/
declare module "dns" {
import * as dnsPromises from "node:dns/promises";
@@ -71,7 +71,7 @@ declare module "dns" {
*/
family?: number | "IPv4" | "IPv6" | undefined;
/**
* One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v22.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be
* One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v24.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be
* passed by bitwise `OR`ing their values.
*/
hints?: number | undefined;
@@ -84,7 +84,7 @@ declare module "dns" {
* When `verbatim`, the resolved addresses are return 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-v22.x/api/cli.html#--dns-result-orderorder).
* {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder).
* @default `verbatim` (addresses are not reordered)
* @since v22.1.0
*/
@@ -133,13 +133,13 @@ declare module "dns" {
* The implementation uses an operating system facility that can associate names
* with addresses and vice versa. This implementation can have subtle but
* important consequences on the behavior of any Node.js program. Please take some
* time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations)
* time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations)
* before using `dns.lookup()`.
*
* Example usage:
*
* ```js
* const dns = require('node:dns');
* import dns from 'node:dns';
* const options = {
* family: 6,
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
@@ -155,7 +155,7 @@ declare module "dns" {
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
* ```
*
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed
* version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties.
* @since v0.1.90
*/
@@ -195,18 +195,18 @@ declare module "dns" {
* If `address` is not a valid IP address, a `TypeError` will be thrown.
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
*
* On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object,
* On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object,
* where `err.code` is the error code.
*
* ```js
* const dns = require('node:dns');
* import dns from 'node:dns';
* dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
* console.log(hostname, service);
* // Prints: localhost ssh
* });
* ```
*
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed
* version, it returns a `Promise` for an `Object` with `hostname` and `service` properties.
* @since v0.11.14
*/
@@ -289,6 +289,15 @@ declare module "dns" {
export interface AnySrvRecord extends SrvRecord {
type: "SRV";
}
export interface TlsaRecord {
certUsage: number;
selector: number;
match: number;
data: ArrayBuffer;
}
export interface AnyTlsaRecord extends TlsaRecord {
type: "TLSA";
}
export interface AnyTxtRecord {
type: "TXT";
entries: string[];
@@ -315,6 +324,7 @@ declare module "dns" {
| AnyPtrRecord
| AnySoaRecord
| AnySrvRecord
| AnyTlsaRecord
| AnyTxtRecord;
/**
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
@@ -323,7 +333,7 @@ declare module "dns" {
*
* <omitted>
*
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object,
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object,
* where `err.code` is one of the `DNS error codes`.
* @since v0.1.27
* @param hostname Host name to resolve.
@@ -383,6 +393,11 @@ declare module "dns" {
rrtype: "SRV",
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "TLSA",
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "TXT",
@@ -393,7 +408,15 @@ declare module "dns" {
rrtype: string,
callback: (
err: NodeJS.ErrnoException | null,
addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[],
addresses:
| string[]
| MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| string[][]
| AnyRecord[],
) => void,
): void;
export namespace resolve {
@@ -403,11 +426,14 @@ declare module "dns" {
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function __promisify__(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function __promisify__(
hostname: string,
rrtype: string,
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
): Promise<
string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | TlsaRecord[] | string[][] | AnyRecord[]
>;
}
/**
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function
@@ -609,6 +635,33 @@ declare module "dns" {
export namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>;
}
/**
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
* the `hostname`. The `records` argument passed to the `callback` function is an
* array of objects with these properties:
*
* * `certUsage`
* * `selector`
* * `match`
* * `data`
*
* ```js
* {
* certUsage: 3,
* selector: 1,
* match: 1,
* data: [ArrayBuffer]
* }
* ```
* @since v23.9.0, v22.15.0
*/
export function resolveTlsa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
): void;
export namespace resolveTlsa {
function __promisify__(hostname: string): Promise<TlsaRecord[]>;
}
/**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a
* two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
@@ -664,8 +717,8 @@ declare module "dns" {
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
* array of host names.
*
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, where `err.code` is
* one of the [DNS error codes](https://nodejs.org/docs/latest-v22.x/api/dns.html#error-codes).
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, where `err.code` is
* one of the [DNS error codes](https://nodejs.org/docs/latest-v24.x/api/dns.html#error-codes).
* @since v0.1.16
*/
export function reverse(
@@ -673,7 +726,7 @@ declare module "dns" {
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void,
): void;
/**
* Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options).
* Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options).
* The value could be:
*
* * `ipv4first`: for `order` defaulting to `ipv4first`.
@@ -728,7 +781,7 @@ declare module "dns" {
*/
export function getServers(): string[];
/**
* Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options).
* Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options).
* The value could be:
*
* * `ipv4first`: sets default `order` to `ipv4first`.
@@ -736,8 +789,8 @@ declare module "dns" {
* * `verbatim`: sets default `order` to `verbatim`.
*
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
* priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--dns-result-orderorder). When using
* [worker threads](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main
* priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). When using
* [worker threads](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main
* thread won't affect the default dns orders in workers.
* @since v16.4.0, v14.18.0
* @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`.
@@ -783,11 +836,11 @@ declare module "dns" {
* An independent resolver for DNS requests.
*
* Creating a new resolver uses the default server settings. Setting
* the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnssetserversservers) does not affect
* the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnssetserversservers) does not affect
* other resolvers:
*
* ```js
* const { Resolver } = require('node:dns');
* import { Resolver } from 'node:dns';
* const resolver = new Resolver();
* resolver.setServers(['4.4.4.4']);
*
@@ -838,6 +891,7 @@ declare module "dns" {
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTlsa: typeof resolveTlsa;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
/**

View File

@@ -1,7 +1,7 @@
/**
* The `dns.promises` API provides an alternative set of asynchronous DNS methods
* that return `Promise` objects rather than using callbacks. The API is accessible
* via `require('node:dns').promises` or `require('node:dns/promises')`.
* via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`.
* @since v10.6.0
*/
declare module "dns/promises" {
@@ -20,6 +20,7 @@ declare module "dns/promises" {
ResolveWithTtlOptions,
SoaRecord,
SrvRecord,
TlsaRecord,
} from "node:dns";
/**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
@@ -60,7 +61,7 @@ declare module "dns/promises" {
* Example usage:
*
* ```js
* const dns = require('node:dns');
* import dns from 'node:dns';
* const dnsPromises = dns.promises;
* const options = {
* family: 6,
@@ -96,7 +97,7 @@ declare module "dns/promises" {
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
*
* ```js
* const dnsPromises = require('node:dns').promises;
* import dnsPromises from 'node:dns';
* dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
* console.log(result.hostname, result.service);
* // Prints: localhost ssh
@@ -137,11 +138,14 @@ declare module "dns/promises" {
function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function resolve(
hostname: string,
rrtype: string,
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
): Promise<
string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | TlsaRecord[] | string[][] | AnyRecord[]
>;
/**
* Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4
* addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
@@ -292,6 +296,27 @@ declare module "dns/promises" {
* @since v10.6.0
*/
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
/**
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
* the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions
* with these properties:
*
* * `certUsage`
* * `selector`
* * `match`
* * `data`
*
* ```js
* {
* certUsage: 3,
* selector: 1,
* match: 1,
* data: [ArrayBuffer]
* }
* ```
* @since v23.9.0, v22.15.0
*/
function resolveTlsa(hostname: string): Promise<TlsaRecord[]>;
/**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array
* of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
@@ -394,8 +419,8 @@ declare module "dns/promises" {
* other resolvers:
*
* ```js
* const { Resolver } = require('node:dns').promises;
* const resolver = new Resolver();
* import { promises } from 'node:dns';
* const resolver = new promises.Resolver();
* resolver.setServers(['4.4.4.4']);
*
* // This request will use the server at 4.4.4.4, independent of global settings.
@@ -450,6 +475,7 @@ declare module "dns/promises" {
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTlsa: typeof resolveTlsa;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
/**

View File

@@ -1,77 +1,50 @@
export {}; // Don't export anything!
// Make this a module
export {};
//// DOM-like Events
// NB: The Event / EventTarget / EventListener implementations below were copied
// from lib.dom.d.ts, then edited to reflect Node's documentation at
// https://nodejs.org/api/events.html#class-eventtarget.
// Please read that link to understand important implementation differences.
// Conditional type aliases, which are later merged into the global scope.
// Will either be empty if the relevant web library is already present, or the @types/node definition otherwise.
// This conditional type will be the existing global Event in a browser, or
// the copy below in a Node environment.
type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {}
: {
/** This is not used in Node.js and is provided purely for completeness. */
readonly bubbles: boolean;
/** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
cancelBubble: () => void;
/** True if the event was created with the cancelable option */
readonly cancelable: boolean;
/** This is not used in Node.js and is provided purely for completeness. */
readonly composed: boolean;
/** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
composedPath(): [EventTarget?];
/** Alias for event.target. */
readonly currentTarget: EventTarget | null;
/** Is true if cancelable is true and event.preventDefault() has been called. */
readonly defaultPrevented: boolean;
/** This is not used in Node.js and is provided purely for completeness. */
readonly eventPhase: 0 | 2;
/** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
readonly isTrusted: boolean;
/** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
preventDefault(): void;
/** This is not used in Node.js and is provided purely for completeness. */
returnValue: boolean;
/** Alias for event.target. */
readonly srcElement: EventTarget | null;
/** Stops the invocation of event listeners after the current one completes. */
stopImmediatePropagation(): void;
/** This is not used in Node.js and is provided purely for completeness. */
stopPropagation(): void;
/** The `EventTarget` dispatching the event */
readonly target: EventTarget | null;
/** The millisecond timestamp when the Event object was created. */
readonly timeStamp: number;
/** Returns the type of event, e.g. "click", "hashchange", or "submit". */
readonly type: string;
};
type __Event = typeof globalThis extends { onmessage: any } ? {} : Event;
interface Event {
readonly bubbles: boolean;
cancelBubble: boolean;
readonly cancelable: boolean;
readonly composed: boolean;
composedPath(): [EventTarget?];
readonly currentTarget: EventTarget | null;
readonly defaultPrevented: boolean;
readonly eventPhase: 0 | 2;
initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;
readonly isTrusted: boolean;
preventDefault(): void;
readonly returnValue: boolean;
readonly srcElement: EventTarget | null;
stopImmediatePropagation(): void;
stopPropagation(): void;
readonly target: EventTarget | null;
readonly timeStamp: number;
readonly type: string;
}
// See comment above explaining conditional type
type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {}
: {
/**
* Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
*
* If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
*
* The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
* Specifically, the `capture` option is used as part of the key when registering a `listener`.
* Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
*/
addEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: AddEventListenerOptions | boolean,
): void;
/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
dispatchEvent(event: Event): boolean;
/** Removes the event listener in target's event listener list with the same type, callback, and options. */
removeEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: EventListenerOptions | boolean,
): void;
};
type __CustomEvent<T = any> = typeof globalThis extends { onmessage: any } ? {} : CustomEvent<T>;
interface CustomEvent<T = any> extends Event {
readonly detail: T;
}
type __EventTarget = typeof globalThis extends { onmessage: any } ? {} : EventTarget;
interface EventTarget {
addEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: AddEventListenerOptions | boolean,
): void;
dispatchEvent(event: Event): boolean;
removeEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: EventListenerOptions | boolean,
): void;
}
interface EventInit {
bubbles?: boolean;
@@ -79,17 +52,17 @@ interface EventInit {
composed?: boolean;
}
interface CustomEventInit<T = any> extends EventInit {
detail?: T;
}
interface EventListenerOptions {
/** Not directly used by Node.js. Added for API completeness. Default: `false`. */
capture?: boolean;
}
interface AddEventListenerOptions extends EventListenerOptions {
/** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */
once?: boolean;
/** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */
passive?: boolean;
/** The listener will be removed when the given AbortSignal object's `abort()` method is called. */
signal?: AbortSignal;
}
@@ -101,24 +74,26 @@ interface EventListenerObject {
handleEvent(object: Event): void;
}
import {} from "events"; // Make this an ambient declaration
// Merge conditional interfaces into global scope, and conditionally declare global constructors.
declare global {
/** An event which takes place in the DOM. */
interface Event extends __Event {}
var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T
: {
prototype: __Event;
new(type: string, eventInitDict?: EventInit): __Event;
prototype: Event;
new(type: string, eventInitDict?: EventInit): Event;
};
interface CustomEvent<T = any> extends __CustomEvent<T> {}
var CustomEvent: typeof globalThis extends { onmessage: any; CustomEvent: infer T } ? T
: {
prototype: CustomEvent;
new<T>(type: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
};
/**
* EventTarget is a DOM interface implemented by objects that can
* receive events and may have listeners for them.
*/
interface EventTarget extends __EventTarget {}
var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T
: {
prototype: __EventTarget;
new(): __EventTarget;
prototype: EventTarget;
new(): EventTarget;
};
}

View File

@@ -12,7 +12,7 @@
* will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to
* exit immediately with an error code.
* @deprecated Since v1.4.2 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/domain.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/domain.js)
*/
declare module "domain" {
import EventEmitter = require("node:events");
@@ -63,8 +63,8 @@ declare module "domain" {
* This is the most basic way to use a domain.
*
* ```js
* const domain = require('node:domain');
* const fs = require('node:fs');
* import domain from 'node:domain';
* import fs from 'node:fs';
* const d = domain.create();
* d.on('error', (er) => {
* console.error('Caught error!', er);

11
node_modules/@types/node/events.d.ts generated vendored
View File

@@ -32,7 +32,7 @@
* });
* myEmitter.emit('event');
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/events.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/events.js)
*/
declare module "events" {
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
@@ -304,12 +304,12 @@ declare module "events" {
emitter: NodeJS.EventEmitter,
eventName: string | symbol,
options?: StaticEventEmitterIteratorOptions,
): AsyncIterableIterator<any[]>;
): NodeJS.AsyncIterator<any[]>;
static on(
emitter: EventTarget,
eventName: string,
options?: StaticEventEmitterIteratorOptions,
): AsyncIterableIterator<any[]>;
): NodeJS.AsyncIterator<any[]>;
/**
* A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`.
*
@@ -396,7 +396,7 @@ declare module "events" {
* ```
* @since v15.4.0
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
* @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
* @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
* objects.
*/
static setMaxListeners(n?: number, ...eventTargets: Array<EventTarget | NodeJS.EventEmitter>): void;
@@ -431,7 +431,6 @@ declare module "events" {
* }
* ```
* @since v20.5.0
* @experimental
* @return Disposable that removes the `abort` listener.
*/
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
@@ -768,7 +767,7 @@ declare module "events" {
setMaxListeners(n: number): this;
/**
* Returns the current max listener value for the `EventEmitter` which is either
* set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}.
* set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}.
* @since v1.0.0
*/
getMaxListeners(): number;

346
node_modules/@types/node/fs.d.ts generated vendored
View File

@@ -16,7 +16,7 @@
*
* All file system operations have synchronous, callback, and promise-based
* forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/fs.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js)
*/
declare module "fs" {
import * as stream from "node:stream";
@@ -198,7 +198,7 @@ declare module "fs" {
* the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s.
* @since v10.10.0
*/
export class Dirent {
export class Dirent<Name extends string | Buffer = string> {
/**
* Returns `true` if the `fs.Dirent` object describes a regular file.
* @since v10.10.0
@@ -241,18 +241,12 @@ declare module "fs" {
* value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}.
* @since v10.10.0
*/
name: string;
name: Name;
/**
* The base path that this `fs.Dirent` object refers to.
* @since v20.12.0
* The path to the parent directory of the file this `fs.Dirent` object refers to.
* @since v20.12.0, v18.20.0
*/
parentPath: string;
/**
* Alias for `dirent.parentPath`.
* @since v20.1.0
* @deprecated Since v20.12.0
*/
path: string;
}
/**
* A class representing a directory stream.
@@ -284,7 +278,7 @@ declare module "fs" {
/**
* Asynchronously iterates over the directory via `readdir(3)` until all entries have been read.
*/
[Symbol.asyncIterator](): AsyncIterableIterator<Dirent>;
[Symbol.asyncIterator](): NodeJS.AsyncIterator<Dirent>;
/**
* Asynchronously close the directory's underlying resource handle.
* Subsequent reads will result in errors.
@@ -438,57 +432,47 @@ declare module "fs" {
* 2. close
* 3. ready
*/
addListener(event: "close", listener: () => void): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
addListener(event: "end", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "open", listener: (fd: number) => void): this;
addListener(event: "pause", listener: () => void): this;
addListener(event: "readable", listener: () => void): this;
addListener(event: "ready", listener: () => void): this;
addListener(event: "resume", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this;
on(event: "end", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "open", listener: (fd: number) => void): this;
on(event: "pause", listener: () => void): this;
on(event: "readable", listener: () => void): this;
on(event: "ready", listener: () => void): this;
on(event: "resume", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this;
once(event: "end", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "open", listener: (fd: number) => void): this;
once(event: "pause", listener: () => void): this;
once(event: "readable", listener: () => void): this;
once(event: "ready", listener: () => void): this;
once(event: "resume", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependListener(event: "end", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "open", listener: (fd: number) => void): this;
prependListener(event: "pause", listener: () => void): this;
prependListener(event: "readable", listener: () => void): this;
prependListener(event: "ready", listener: () => void): this;
prependListener(event: "resume", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "open", listener: (fd: number) => void): this;
prependOnceListener(event: "pause", listener: () => void): this;
prependOnceListener(event: "readable", listener: () => void): this;
prependOnceListener(event: "ready", listener: () => void): this;
prependOnceListener(event: "resume", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
addListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
on<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
once<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
prependListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
prependOnceListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
}
/**
* The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted.
*/
type ReadStreamEvents = {
close: () => void;
data: (chunk: Buffer | string) => void;
end: () => void;
error: (err: Error) => void;
open: (fd: number) => void;
pause: () => void;
readable: () => void;
ready: () => void;
resume: () => void;
} & CustomEvents;
/**
* string & {} allows to allow any kind of strings for the event
* but still allows to have auto completion for the normal events.
*/
type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void };
/**
* The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted.
*/
type WriteStreamEvents = {
close: () => void;
drain: () => void;
error: (err: Error) => void;
finish: () => void;
open: (fd: number) => void;
pipe: (src: stream.Readable) => void;
ready: () => void;
unpipe: (src: stream.Readable) => void;
} & CustomEvents;
/**
* * Extends `stream.Writable`
*
@@ -527,51 +511,11 @@ declare module "fs" {
* 2. close
* 3. ready
*/
addListener(event: "close", listener: () => void): this;
addListener(event: "drain", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "finish", listener: () => void): this;
addListener(event: "open", listener: (fd: number) => void): this;
addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
addListener(event: "ready", listener: () => void): this;
addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "drain", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "open", listener: (fd: number) => void): this;
on(event: "pipe", listener: (src: stream.Readable) => void): this;
on(event: "ready", listener: () => void): this;
on(event: "unpipe", listener: (src: stream.Readable) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "drain", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "finish", listener: () => void): this;
once(event: "open", listener: (fd: number) => void): this;
once(event: "pipe", listener: (src: stream.Readable) => void): this;
once(event: "ready", listener: () => void): this;
once(event: "unpipe", listener: (src: stream.Readable) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "drain", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "finish", listener: () => void): this;
prependListener(event: "open", listener: (fd: number) => void): this;
prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependListener(event: "ready", listener: () => void): this;
prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "finish", listener: () => void): this;
prependOnceListener(event: "open", listener: (fd: number) => void): this;
prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: "ready", listener: () => void): this;
prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
addListener<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
on<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
once<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
prependListener<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
prependOnceListener<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
}
/**
* Asynchronously rename file at `oldPath` to the pathname provided
@@ -631,7 +575,7 @@ declare module "fs" {
* @since v0.8.6
* @param [len=0]
*/
export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void;
export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void;
/**
* Asynchronous truncate(2) - Truncate a file to a specified length.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@@ -643,7 +587,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param len If not specified, defaults to `0`.
*/
function __promisify__(path: PathLike, len?: number | null): Promise<void>;
function __promisify__(path: PathLike, len?: number): Promise<void>;
}
/**
* Truncates the file. Returns `undefined`. A file descriptor can also be
@@ -654,7 +598,7 @@ declare module "fs" {
* @since v0.8.6
* @param [len=0]
*/
export function truncateSync(path: PathLike, len?: number | null): void;
export function truncateSync(path: PathLike, len?: number): void;
/**
* Truncates the file descriptor. No arguments other than a possible exception are
* given to the completion callback.
@@ -698,7 +642,7 @@ declare module "fs" {
* @since v0.8.6
* @param [len=0]
*/
export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void;
export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void;
/**
* Asynchronous ftruncate(2) - Truncate a file to a specified length.
* @param fd A file descriptor.
@@ -710,7 +654,7 @@ declare module "fs" {
* @param fd A file descriptor.
* @param len If not specified, defaults to `0`.
*/
function __promisify__(fd: number, len?: number | null): Promise<void>;
function __promisify__(fd: number, len?: number): Promise<void>;
}
/**
* Truncates the file descriptor. Returns `undefined`.
@@ -720,7 +664,7 @@ declare module "fs" {
* @since v0.8.6
* @param [len=0]
*/
export function ftruncateSync(fd: number, len?: number | null): void;
export function ftruncateSync(fd: number, len?: number): void;
/**
* Asynchronously changes owner and group of a file. No arguments other than a
* possible exception are given to the completion callback.
@@ -1900,7 +1844,7 @@ declare module "fs" {
* The `fs.mkdtemp()` method will append the six randomly selected characters
* directly to the `prefix` string. For instance, given a directory `/tmp`, if the
* intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator
* (`require('node:path').sep`).
* (`import { sep } from 'node:path'`).
*
* ```js
* import { tmpdir } from 'node:os';
@@ -2090,6 +2034,20 @@ declare module "fs" {
},
callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void,
): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
*/
export function readdir(
path: PathLike,
options: {
encoding: "buffer";
withFileTypes: true;
recursive?: boolean | undefined;
},
callback: (err: NodeJS.ErrnoException | null, files: Dirent<Buffer>[]) => void,
): void;
export namespace readdir {
/**
* Asynchronous readdir(3) - read a directory.
@@ -2149,6 +2107,19 @@ declare module "fs" {
recursive?: boolean | undefined;
},
): Promise<Dirent[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
*/
function __promisify__(
path: PathLike,
options: {
encoding: "buffer";
withFileTypes: true;
recursive?: boolean | undefined;
},
): Promise<Dirent<Buffer>[]>;
}
/**
* Reads the contents of the directory.
@@ -2216,6 +2187,19 @@ declare module "fs" {
recursive?: boolean | undefined;
},
): Dirent[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
*/
export function readdirSync(
path: PathLike,
options: {
encoding: "buffer";
withFileTypes: true;
recursive?: boolean | undefined;
},
): Dirent<Buffer>[];
/**
* Closes the file descriptor. No arguments other than a possible exception are
* given to the completion callback.
@@ -2369,6 +2353,20 @@ declare module "fs" {
* @since v0.1.96
*/
export function fsyncSync(fd: number): void;
export interface WriteOptions {
/**
* @default 0
*/
offset?: number | undefined;
/**
* @default `buffer.byteLength - offset`
*/
length?: number | undefined;
/**
* @default null
*/
position?: number | undefined | null;
}
/**
* Write `buffer` to the file specified by `fd`.
*
@@ -2437,6 +2435,20 @@ declare module "fs" {
buffer: TBuffer,
callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param options An object with the following properties:
* * `offset` The part of the buffer to be written. If not supplied, defaults to `0`.
* * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
* * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
export function write<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
options: WriteOptions,
callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
): void;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
@@ -2491,6 +2503,22 @@ declare module "fs" {
bytesWritten: number;
buffer: TBuffer;
}>;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param options An object with the following properties:
* * `offset` The part of the buffer to be written. If not supplied, defaults to `0`.
* * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
* * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer?: TBuffer,
options?: WriteOptions,
): Promise<{
bytesWritten: number;
buffer: TBuffer;
}>;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
@@ -2594,6 +2622,17 @@ declare module "fs" {
options: ReadAsyncOptions<TBuffer>,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
): void;
export function read<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
options: ReadSyncOptions,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
): void;
export function read<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
): void;
export function read(
fd: number,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void,
@@ -2611,7 +2650,7 @@ declare module "fs" {
buffer: TBuffer,
offset: number,
length: number,
position: number | null,
position: ReadPosition | null,
): Promise<{
bytesRead: number;
buffer: TBuffer;
@@ -2723,7 +2762,7 @@ declare module "fs" {
} & Abortable)
| undefined
| null,
callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void,
callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void,
): void;
/**
* Asynchronously reads the entire contents of a file.
@@ -2758,7 +2797,7 @@ declare module "fs" {
| BufferEncoding
| undefined
| null,
callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void,
callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void,
): void;
/**
* Asynchronously reads the entire contents of a file.
@@ -2767,7 +2806,7 @@ declare module "fs" {
*/
export function readFile(
path: PathOrFileDescriptor,
callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void,
callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void,
): void;
export namespace readFile {
/**
@@ -2783,7 +2822,7 @@ declare module "fs" {
encoding?: null | undefined;
flag?: string | undefined;
} | null,
): Promise<Buffer>;
): Promise<NonSharedBuffer>;
/**
* 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.
@@ -2817,7 +2856,7 @@ declare module "fs" {
})
| BufferEncoding
| null,
): Promise<string | Buffer>;
): Promise<string | NonSharedBuffer>;
}
/**
* Returns the contents of the `path`.
@@ -2849,7 +2888,7 @@ declare module "fs" {
encoding?: null | undefined;
flag?: string | undefined;
} | null,
): Buffer;
): 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.
@@ -2881,7 +2920,7 @@ declare module "fs" {
})
| BufferEncoding
| null,
): string | Buffer;
): string | NonSharedBuffer;
export type WriteFileOptions =
| (
& ObjectEncodingOptions
@@ -3156,7 +3195,7 @@ declare module "fs" {
* stat object:
*
* ```js
* import { watchFile } from 'fs';
* import { watchFile } from 'node:fs';
*
* watchFile('message.text', (curr, prev) => {
* console.log(`the current mtime is: ${curr.mtime}`);
@@ -3845,9 +3884,6 @@ declare module "fs" {
flush?: boolean | undefined;
}
/**
* Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream
* returned by this method has a default `highWaterMark` of 64 KiB.
*
* `options` can include `start` and `end` values to read a range of bytes from
* the file instead of the entire file. Both `start` and `end` are inclusive and
* start counting at 0, allowed values are in the
@@ -4065,7 +4101,7 @@ declare module "fs" {
export function writev(
fd: number,
buffers: readonly NodeJS.ArrayBufferView[],
position: number,
position: number | null,
cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void,
): void;
export interface WriteVResult {
@@ -4110,7 +4146,7 @@ declare module "fs" {
export function readv(
fd: number,
buffers: readonly NodeJS.ArrayBufferView[],
position: number,
position: number | null,
cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void,
): void;
export interface ReadVResult {
@@ -4158,7 +4194,6 @@ declare module "fs" {
* blob.stream();
* ```
* @since v19.8.0
* @experimental
*/
export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise<Blob>;
@@ -4314,38 +4349,53 @@ declare module "fs" {
*/
export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void;
export interface GlobOptions {
interface _GlobOptions<T extends Dirent | string> {
/**
* Current working directory.
* @default process.cwd()
*/
cwd?: string | undefined;
/**
* Function to filter out files/directories. Return true to exclude the item, false to include it.
*/
exclude?: ((fileName: string) => boolean) | 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
* `true` to exclude the item, `false` to include it.
* @default undefined
*/
exclude?: ((fileName: T) => boolean) | readonly string[] | undefined;
}
export interface GlobOptionsWithFileTypes extends GlobOptions {
export interface GlobOptions extends _GlobOptions<Dirent | string> {}
export interface GlobOptionsWithFileTypes extends _GlobOptions<Dirent> {
withFileTypes: true;
}
export interface GlobOptionsWithoutFileTypes extends GlobOptions {
export interface GlobOptionsWithoutFileTypes extends _GlobOptions<string> {
withFileTypes?: false | undefined;
}
/**
* Retrieves the files matching the specified pattern.
*
* ```js
* import { glob } from 'node:fs';
*
* glob('*.js', (err, matches) => {
* if (err) throw err;
* console.log(matches);
* });
* ```
* @since v22.0.0
*/
export function glob(
pattern: string | string[],
pattern: string | readonly string[],
callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void,
): void;
export function glob(
pattern: string | string[],
pattern: string | readonly string[],
options: GlobOptionsWithFileTypes,
callback: (
err: NodeJS.ErrnoException | null,
@@ -4353,7 +4403,7 @@ declare module "fs" {
) => void,
): void;
export function glob(
pattern: string | string[],
pattern: string | readonly string[],
options: GlobOptionsWithoutFileTypes,
callback: (
err: NodeJS.ErrnoException | null,
@@ -4361,7 +4411,7 @@ declare module "fs" {
) => void,
): void;
export function glob(
pattern: string | string[],
pattern: string | readonly string[],
options: GlobOptions,
callback: (
err: NodeJS.ErrnoException | null,
@@ -4369,19 +4419,25 @@ declare module "fs" {
) => void,
): void;
/**
* Retrieves the files matching the specified pattern.
* ```js
* import { globSync } from 'node:fs';
*
* console.log(globSync('*.js'));
* ```
* @since v22.0.0
* @returns paths of files that match the pattern.
*/
export function globSync(pattern: string | string[]): string[];
export function globSync(pattern: string | readonly string[]): string[];
export function globSync(
pattern: string | string[],
pattern: string | readonly string[],
options: GlobOptionsWithFileTypes,
): Dirent[];
export function globSync(
pattern: string | string[],
pattern: string | readonly string[],
options: GlobOptionsWithoutFileTypes,
): string[];
export function globSync(
pattern: string | string[],
pattern: string | readonly string[],
options: GlobOptions,
): Dirent[] | string[];
}

View File

@@ -29,6 +29,7 @@ declare module "fs/promises" {
OpenDirOptions,
OpenMode,
PathLike,
ReadPosition,
ReadStream,
ReadVResult,
RmDirOptions,
@@ -69,9 +70,9 @@ declare module "fs/promises" {
* @default `buffer.byteLength`
*/
length?: number | null;
position?: number | null;
position?: ReadPosition | null;
}
interface CreateReadStreamOptions {
interface CreateReadStreamOptions extends Abortable {
encoding?: BufferEncoding | null | undefined;
autoClose?: boolean | undefined;
emitClose?: boolean | undefined;
@@ -87,13 +88,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 {
/**
@@ -112,7 +106,7 @@ declare module "fs/promises" {
appendFile(
data: string | Uint8Array,
options?:
| (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined })
| (ObjectEncodingOptions & Abortable)
| BufferEncoding
| null,
): Promise<void>;
@@ -236,11 +230,16 @@ declare module "fs/promises" {
buffer: T,
offset?: number | null,
length?: number | null,
position?: number | null,
position?: ReadPosition | null,
): Promise<FileReadResult<T>>;
read<T extends NodeJS.ArrayBufferView = Buffer>(
buffer: T,
options?: FileReadOptions<T>,
): Promise<FileReadResult<T>>;
read<T extends NodeJS.ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>>;
/**
* 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.
@@ -261,9 +260,8 @@ declare module "fs/promises" {
* While the `ReadableStream` will read the file to completion, it will not
* close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method.
* @since v17.0.0
* @experimental
*/
readableWebStream(options?: ReadableWebStreamOptions): ReadableStream;
readableWebStream(): ReadableStream;
/**
* Asynchronously reads the entire contents of a file.
*
@@ -279,36 +277,26 @@ declare module "fs/promises" {
* data will be a string.
*/
readFile(
options?: {
encoding?: null | undefined;
flag?: OpenMode | undefined;
} | null,
options?:
| ({ encoding?: null | undefined } & Abortable)
| null,
): Promise<Buffer>;
/**
* Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.
* The `FileHandle` must have been opened for reading.
* @param options An object that may contain an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
readFile(
options:
| {
encoding: BufferEncoding;
flag?: OpenMode | undefined;
}
| ({ encoding: BufferEncoding } & Abortable)
| BufferEncoding,
): Promise<string>;
/**
* Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.
* The `FileHandle` must have been opened for reading.
* @param options An object that may contain an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
readFile(
options?:
| (ObjectEncodingOptions & {
flag?: OpenMode | undefined;
})
| (ObjectEncodingOptions & Abortable)
| BufferEncoding
| null,
): Promise<string | Buffer>;
@@ -398,7 +386,7 @@ declare module "fs/promises" {
writeFile(
data: string | Uint8Array,
options?:
| (ObjectEncodingOptions & FlagAndOpenMode & Abortable & { flush?: boolean | undefined })
| (ObjectEncodingOptions & Abortable)
| BufferEncoding
| null,
): Promise<void>;
@@ -429,6 +417,13 @@ declare module "fs/promises" {
bytesWritten: number;
buffer: TBuffer;
}>;
write<TBuffer extends Uint8Array>(
buffer: TBuffer,
options?: { offset?: number; length?: number; position?: number },
): Promise<{
bytesWritten: number;
buffer: TBuffer;
}>;
write(
data: string,
position?: number | null,
@@ -723,6 +718,19 @@ declare module "fs/promises" {
recursive?: boolean | undefined;
},
): Promise<Dirent[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a directory. If a URL is provided, it must use the `file:` protocol.
* @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
*/
function readdir(
path: PathLike,
options: {
encoding: "buffer";
withFileTypes: true;
recursive?: boolean | undefined;
},
): Promise<Dirent<Buffer>[]>;
/**
* Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is
* fulfilled with the`linkString` upon success.
@@ -932,7 +940,7 @@ declare module "fs/promises" {
* The `fsPromises.mkdtemp()` method will append the six randomly selected
* characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing
* platform-specific path separator
* (`require('node:path').sep`).
* (`import { sep } from 'node:path'`).
* @since v10.0.0
* @return Fulfills with a string containing the file system path of the newly created temporary directory.
*/
@@ -1174,7 +1182,7 @@ declare module "fs/promises" {
* Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory.
*
* ```js
* const { watch } = require('node:fs/promises');
* import { watch } from 'node:fs/promises';
*
* const ac = new AbortController();
* const { signal } = ac;
@@ -1243,21 +1251,29 @@ declare module "fs/promises" {
*/
function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise<void>;
/**
* Retrieves the files matching the specified pattern.
* ```js
* import { glob } from 'node:fs/promises';
*
* for await (const entry of glob('*.js'))
* console.log(entry);
* ```
* @since v22.0.0
* @returns An AsyncIterator that yields the paths of files
* that match the pattern.
*/
function glob(pattern: string | string[]): AsyncIterableIterator<string>;
function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator<string>;
function glob(
pattern: string | string[],
opt: GlobOptionsWithFileTypes,
): AsyncIterableIterator<Dirent>;
pattern: string | readonly string[],
options: GlobOptionsWithFileTypes,
): NodeJS.AsyncIterator<Dirent>;
function glob(
pattern: string | string[],
opt: GlobOptionsWithoutFileTypes,
): AsyncIterableIterator<string>;
pattern: string | readonly string[],
options: GlobOptionsWithoutFileTypes,
): NodeJS.AsyncIterator<string>;
function glob(
pattern: string | string[],
opt: GlobOptions,
): AsyncIterableIterator<Dirent> | AsyncIterableIterator<string>;
pattern: string | readonly string[],
options: GlobOptions,
): NodeJS.AsyncIterator<Dirent | string>;
}
declare module "node:fs/promises" {
export * from "fs/promises";

540
node_modules/@types/node/globals.d.ts generated vendored
View File

@@ -14,47 +14,16 @@ type _ResponseInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").ResponseInit;
type _WebSocket = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").WebSocket;
type _EventSource = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").EventSource;
type _CloseEvent = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").CloseEvent;
// #endregion Fetch and friends
// Conditional type definitions for webstorage interface, which conflicts with lib.dom otherwise.
type _Storage = typeof globalThis extends { onabort: any } ? {} : {
/**
* Returns the number of key/value pairs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/length)
*/
readonly length: number;
/**
* Removes all key/value pairs, if there are any.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/clear)
*/
clear(): void;
/**
* Returns the current value associated with the given key, or null if the given key does not exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/getItem)
*/
getItem(key: string): string | null;
/**
* Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/key)
*/
key(index: number): string | null;
/**
* Removes the key/value pair with the given key, if a key/value pair with the given key exists.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/removeItem)
*/
removeItem(key: string): void;
/**
* Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
*
* Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/setItem)
*/
setItem(key: string, value: string): void;
[key: string]: any;
};
@@ -62,15 +31,8 @@ type _Storage = typeof globalThis extends { onabort: any } ? {} : {
// #region DOMException
type _DOMException = typeof globalThis extends { onmessage: any } ? {} : NodeDOMException;
interface NodeDOMException extends Error {
/**
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)
*/
readonly code: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */
readonly message: string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */
readonly name: string;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
@@ -130,304 +92,104 @@ interface NodeDOMExceptionConstructor {
// #endregion DOMException
declare global {
// Declare "static" methods in Error
interface ErrorConstructor {
/** Create .stack property on a target object */
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Optional override for formatting stack traces
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
/*-----------------------------------------------*
* *
* GLOBAL *
* *
------------------------------------------------*/
// For backwards compability
interface NodeRequire extends NodeJS.Require {}
interface RequireResolve extends NodeJS.RequireResolve {}
interface NodeModule extends NodeJS.Module {}
var global: typeof globalThis;
var process: NodeJS.Process;
var console: Console;
var __filename: string;
var __dirname: string;
var require: NodeRequire;
var module: NodeModule;
// Same as module.exports
var exports: any;
/**
* Only available if `--expose-gc` is passed to the process.
*/
var gc: undefined | (() => void);
// #region borrowed
// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib
/** A controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
interface ErrorConstructor {
/**
* Returns the AbortSignal object associated with this object.
* Creates a `.stack` property on `targetObject`, which when accessed returns
* a string representing the location in the code at which
* `Error.captureStackTrace()` was called.
*
* ```js
* const myObject = {};
* Error.captureStackTrace(myObject);
* myObject.stack; // Similar to `new Error().stack`
* ```
*
* The first line of the trace will be prefixed with
* `${myObject.name}: ${myObject.message}`.
*
* The optional `constructorOpt` argument accepts a function. If given, all frames
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
* generated stack trace.
*
* The `constructorOpt` argument is useful for hiding implementation
* details of error generation from the user. For instance:
*
* ```js
* function a() {
* b();
* }
*
* function b() {
* c();
* }
*
* function c() {
* // Create an error without stack trace to avoid calculating the stack trace twice.
* const { stackTraceLimit } = Error;
* Error.stackTraceLimit = 0;
* const error = new Error();
* Error.stackTraceLimit = stackTraceLimit;
*
* // Capture the stack trace above function b
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
* throw error;
* }
*
* a();
* ```
*/
readonly signal: AbortSignal;
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
abort(reason?: any): void;
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
/**
* The `Error.stackTraceLimit` property specifies the number of stack frames
* collected by a stack trace (whether generated by `new Error().stack` or
* `Error.captureStackTrace(obj)`).
*
* The default value is `10` but may be set to any valid JavaScript number. Changes
* will affect any stack trace captured _after_ the value has been changed.
*
* If set to a non-number value, or set to a negative number, stack traces will
* not capture any frames.
*/
stackTraceLimit: number;
}
/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
interface AbortSignal extends EventTarget {
/**
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
*/
readonly aborted: boolean;
readonly reason: any;
onabort: null | ((this: AbortSignal, event: Event) => any);
throwIfAborted(): void;
}
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
: {
prototype: AbortController;
new(): AbortController;
};
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
timeout(milliseconds: number): AbortSignal;
any(signals: AbortSignal[]): AbortSignal;
};
// #endregion borrowed
// #region Storage
/**
* This Web Storage API interface provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage)
* Enable this API with the `--expose-gc` CLI flag.
*/
interface Storage extends _Storage {}
var gc: NodeJS.GCFunction | undefined;
// Conditional on `onabort` rather than `onmessage`, in order to exclude lib.webworker
var Storage: typeof globalThis extends { onabort: any; Storage: infer T } ? T
: {
prototype: Storage;
new(): Storage;
};
/**
* A browser-compatible implementation of [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
* Data is stored unencrypted in the file specified by the `--localstorage-file` CLI flag.
* Any modification of this data outside of the Web Storage API is not supported.
* Enable this API with the `--experimental-webstorage` CLI flag.
* @since v22.4.0
*/
var localStorage: Storage;
/**
* A browser-compatible implementation of [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
* Data is stored in memory, with a storage quota of 10 MB.
* Any modification of this data outside of the Web Storage API is not supported.
* Enable this API with the `--experimental-webstorage` CLI flag.
* @since v22.4.0
*/
var sessionStorage: Storage;
// #endregion Storage
// #region Disposable
interface SymbolConstructor {
/**
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement.
*/
readonly dispose: unique symbol;
/**
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement.
*/
readonly asyncDispose: unique symbol;
}
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): PromiseLike<void>;
}
// #endregion Disposable
// #region ArrayLike.at()
interface RelativeIndexable<T> {
/**
* Takes an integer value and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
*/
at(index: number): T | undefined;
}
interface String extends RelativeIndexable<string> {}
interface Array<T> extends RelativeIndexable<T> {}
interface ReadonlyArray<T> extends RelativeIndexable<T> {}
interface Int8Array extends RelativeIndexable<number> {}
interface Uint8Array extends RelativeIndexable<number> {}
interface Uint8ClampedArray extends RelativeIndexable<number> {}
interface Int16Array extends RelativeIndexable<number> {}
interface Uint16Array extends RelativeIndexable<number> {}
interface Int32Array extends RelativeIndexable<number> {}
interface Uint32Array extends RelativeIndexable<number> {}
interface Float32Array extends RelativeIndexable<number> {}
interface Float64Array extends RelativeIndexable<number> {}
interface BigInt64Array extends RelativeIndexable<bigint> {}
interface BigUint64Array extends RelativeIndexable<bigint> {}
// #endregion ArrayLike.at() end
/**
* @since v17.0.0
*
* Creates a deep clone of an object.
*/
function structuredClone<T>(
value: T,
transfer?: { transfer: ReadonlyArray<import("worker_threads").TransferListItem> },
): T;
// #region DOMException
/**
* @since v17.0.0
* An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)
*/
interface DOMException extends _DOMException {}
/**
* @since v17.0.0
*
* The WHATWG `DOMException` class. See [DOMException](https://developer.mozilla.org/docs/Web/API/DOMException) for more details.
*/
var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T
: NodeDOMExceptionConstructor;
// #endregion DOMException
/*----------------------------------------------*
* *
* GLOBAL INTERFACES *
* *
*-----------------------------------------------*/
namespace NodeJS {
interface CallSite {
/**
* Value of "this"
*/
getThis(): unknown;
/**
* Type of "this" as a string.
* This is the name of the function stored in the constructor field of
* "this", if available. Otherwise the object's [[Class]] internal
* property.
*/
getTypeName(): string | null;
/**
* Current function
*/
getFunction(): Function | undefined;
/**
* Name of the current function, typically its name property.
* If a name property is not available an attempt will be made to try
* to infer a name from the function's context.
*/
getFunctionName(): string | null;
/**
* Name of the property [of "this" or one of its prototypes] that holds
* the current function
*/
getMethodName(): string | null;
/**
* Name of the script [if this function was defined in a script]
*/
getFileName(): string | undefined;
/**
* Current line number [if this function was defined in a script]
*/
getLineNumber(): number | null;
/**
* Current column number [if this function was defined in a script]
*/
getColumnNumber(): number | null;
/**
* A call site object representing the location where eval was called
* [if this function was created using a call to eval]
*/
getEnclosingColumnNumber(): number | null;
getEnclosingLineNumber(): number | null;
getEvalOrigin(): string | undefined;
/**
* Is this a toplevel invocation, that is, is "this" the global object?
*/
isToplevel(): boolean;
/**
* Does this call take place in code defined by a call to eval?
*/
isEval(): boolean;
/**
* Is this call in native V8 code?
*/
isNative(): boolean;
/**
* Is this a constructor call?
*/
isConstructor(): boolean;
/**
* is this an async call (i.e. await, Promise.all(), or Promise.any())?
*/
isAsync(): boolean;
/**
* is this an async call to Promise.all()?
*/
isPromiseAll(): boolean;
/**
* returns the index of the promise element that was followed in
* Promise.all() or Promise.any() for async stack traces, or null
* if the CallSite is not an async
*/
getPromiseIndex(): number | null;
getScriptNameOrSourceURL(): string;
getScriptHash(): string;
getEnclosingColumnNumber(): number;
getEnclosingLineNumber(): number;
getFileName(): string | null;
getFunction(): Function | undefined;
getFunctionName(): string | null;
getLineNumber(): number | null;
getMethodName(): string | null;
getPosition(): number;
toString(): string;
getPromiseIndex(): number | null;
getScriptHash(): string;
getScriptNameOrSourceURL(): string | null;
getThis(): unknown;
getTypeName(): string | null;
isAsync(): boolean;
isConstructor(): boolean;
isEval(): boolean;
isNative(): boolean;
isPromiseAll(): boolean;
isToplevel(): boolean;
}
interface ErrnoException extends Error {
@@ -467,63 +229,6 @@ declare global {
unref(): this;
}
type TypedArray =
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| BigUint64Array
| BigInt64Array
| Float32Array
| Float64Array;
type ArrayBufferView = TypedArray | DataView;
interface Require {
(id: string): any;
resolve: RequireResolve;
cache: Dict<NodeModule>;
/**
* @deprecated
*/
extensions: RequireExtensions;
main: Module | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[] | undefined }): string;
paths(request: string): string[] | null;
}
interface RequireExtensions extends Dict<(m: Module, filename: string) => any> {
".js": (m: Module, filename: string) => any;
".json": (m: Module, filename: string) => any;
".node": (m: Module, filename: string) => any;
}
interface Module {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: Require;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */
parent: Module | null | undefined;
children: Module[];
/**
* @since v11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}
interface Dict<T> {
[key: string]: T | undefined;
}
@@ -531,8 +236,78 @@ declare global {
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
interface GCFunction {
(minor?: boolean): void;
(options: NodeJS.GCOptions & { execution: "async" }): Promise<void>;
(options: NodeJS.GCOptions): void;
}
interface GCOptions {
execution?: "sync" | "async" | undefined;
flavor?: "regular" | "last-resort" | undefined;
type?: "major-snapshot" | "major" | "minor" | undefined;
filename?: string | undefined;
}
/** An iterable iterator returned by the Node.js API. */
interface Iterator<T, TReturn = undefined, TNext = any> extends IteratorObject<T, TReturn, TNext> {
[Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>;
}
/** An async iterable iterator returned by the Node.js API. */
interface AsyncIterator<T, TReturn = undefined, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
[Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>;
}
}
// Global DOM types
interface DOMException extends _DOMException {}
var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T
: NodeDOMExceptionConstructor;
// #region AbortController
interface AbortController {
readonly signal: AbortSignal;
abort(reason?: any): void;
}
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
: {
prototype: AbortController;
new(): AbortController;
};
interface AbortSignal extends EventTarget {
readonly aborted: boolean;
onabort: ((this: AbortSignal, ev: Event) => any) | null;
readonly reason: any;
throwIfAborted(): void;
}
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
any(signals: AbortSignal[]): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
// #endregion AbortController
// #region Storage
interface Storage extends _Storage {}
// Conditional on `onabort` rather than `onmessage`, in order to exclude lib.webworker
var Storage: typeof globalThis extends { onabort: any; Storage: infer T } ? T
: {
prototype: Storage;
new(): Storage;
};
var localStorage: Storage;
var sessionStorage: Storage;
// #endregion Storage
// #region fetch
interface RequestInit extends _RequestInit {}
function fetch(
@@ -571,9 +346,6 @@ declare global {
: typeof import("undici-types").Headers;
interface MessageEvent extends _MessageEvent {}
/**
* @since v15.0.0
*/
var MessageEvent: typeof globalThis extends {
onmessage: any;
MessageEvent: infer T;
@@ -585,11 +357,11 @@ declare global {
: typeof import("undici-types").WebSocket;
interface EventSource extends _EventSource {}
/**
* Only available through the [--experimental-eventsource](https://nodejs.org/api/cli.html#--experimental-eventsource) flag.
*
* @since v22.3.0
*/
var EventSource: typeof globalThis extends { onmessage: any; EventSource: infer T } ? T
: typeof import("undici-types").EventSource;
interface CloseEvent extends _CloseEvent {}
var CloseEvent: typeof globalThis extends { onmessage: any; CloseEvent: infer T } ? T
: typeof import("undici-types").CloseEvent;
// #endregion fetch
}

View File

@@ -1 +0,0 @@
declare var global: typeof globalThis;

168
node_modules/@types/node/http.d.ts generated vendored
View File

@@ -1,5 +1,5 @@
/**
* To use the HTTP server and client one must `require('node:http')`.
* To use the HTTP server and client one must import the `node:http` module.
*
* The HTTP interfaces in Node.js are designed to support many features
* of the protocol which have been traditionally difficult to use.
@@ -37,17 +37,18 @@
* 'Host', 'example.com',
* 'accepT', '*' ]
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js)
*/
declare module "http" {
import * as stream from "node:stream";
import { URL } from "node:url";
import { LookupOptions } from "node:dns";
import { EventEmitter } from "node:events";
import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net";
import { LookupFunction, NetConnectOpts, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net";
// incoming headers will never contain number
interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {
accept?: string | undefined;
"accept-encoding"?: string | undefined;
"accept-language"?: string | undefined;
"accept-patch"?: string | undefined;
"accept-ranges"?: string | undefined;
@@ -94,6 +95,10 @@ declare module "http" {
range?: string | undefined;
referer?: string | undefined;
"retry-after"?: string | undefined;
"sec-fetch-site"?: string | undefined;
"sec-fetch-mode"?: string | undefined;
"sec-fetch-user"?: string | undefined;
"sec-fetch-dest"?: string | undefined;
"sec-websocket-accept"?: string | undefined;
"sec-websocket-extensions"?: string | undefined;
"sec-websocket-key"?: string | undefined;
@@ -141,6 +146,7 @@ declare module "http" {
"content-range"?: string | undefined;
"content-security-policy"?: string | undefined;
"content-security-policy-report-only"?: string | undefined;
"content-type"?: string | undefined;
cookie?: string | string[] | undefined;
dav?: string | string[] | undefined;
dnt?: string | undefined;
@@ -161,7 +167,7 @@ declare module "http" {
location?: string | undefined;
"max-forwards"?: string | undefined;
origin?: string | undefined;
prgama?: string | string[] | undefined;
pragma?: string | string[] | undefined;
"proxy-authenticate"?: string | string[] | undefined;
"proxy-authorization"?: string | undefined;
"public-key-pins"?: string | undefined;
@@ -206,7 +212,7 @@ declare module "http" {
| undefined;
defaultPort?: number | string | undefined;
family?: number | undefined;
headers?: OutgoingHttpHeaders | undefined;
headers?: OutgoingHttpHeaders | readonly string[] | undefined;
hints?: LookupOptions["hints"];
host?: string | null | undefined;
hostname?: string | null | undefined;
@@ -222,6 +228,7 @@ declare module "http" {
path?: string | null | undefined;
port?: number | string | null | undefined;
protocol?: string | null | undefined;
setDefaultHeaders?: boolean | undefined;
setHost?: boolean | undefined;
signal?: AbortSignal | undefined;
socketPath?: string | undefined;
@@ -231,7 +238,7 @@ declare module "http" {
}
interface ServerOptions<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse,
> {
/**
* Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`.
@@ -267,6 +274,13 @@ declare module "http" {
* @default 30000
*/
connectionsCheckingInterval?: number | undefined;
/**
* Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client.
* See {@link Server.headersTimeout} for more information.
* @default 60000
* @since 18.0.0
*/
headersTimeout?: number | undefined;
/**
* Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`.
* This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`.
@@ -294,6 +308,13 @@ declare module "http" {
* @since v16.5.0
*/
noDelay?: boolean | undefined;
/**
* If set to `true`, it forces the server to respond with a 400 (Bad Request) status code
* to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification).
* @default true
* @since 20.0.0
*/
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])`.
@@ -312,17 +333,23 @@ declare module "http" {
* If the header's value is an array, the items will be joined using `; `.
*/
uniqueHeaders?: Array<string | string[]> | undefined;
/**
* If set to `true`, an error is thrown when writing to an HTTP response which does not have a body.
* @default false
* @since v18.17.0, v20.2.0
*/
rejectNonStandardBodyWrites?: boolean | undefined;
}
type RequestListener<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse,
> = (req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }) => void;
/**
* @since v0.1.17
*/
class Server<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse,
> extends NetServer {
constructor(requestListener?: RequestListener<Request, Response>);
constructor(options: ServerOptions<Request, Response>, requestListener?: RequestListener<Request, Response>);
@@ -340,8 +367,8 @@ declare module "http" {
* @since v0.9.12
* @param [msecs=0 (no timeout)]
*/
setTimeout(msecs?: number, callback?: () => void): this;
setTimeout(callback: () => void): this;
setTimeout(msecs?: number, callback?: (socket: Socket) => void): this;
setTimeout(callback: (socket: Socket) => void): this;
/**
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
* @since v0.7.0
@@ -588,6 +615,42 @@ declare module "http" {
* @param value Header value
*/
setHeader(name: string, value: number | string | readonly string[]): this;
/**
* Sets multiple header values for implicit headers. headers must be an instance of
* `Headers` or `Map`, if a header already exists in the to-be-sent headers, its
* value will be replaced.
*
* ```js
* const headers = new Headers({ foo: 'bar' });
* outgoingMessage.setHeaders(headers);
* ```
*
* or
*
* ```js
* const headers = new Map([['foo', 'bar']]);
* outgoingMessage.setHeaders(headers);
* ```
*
* When headers have been set with `outgoingMessage.setHeaders()`, they will be
* merged with any headers passed to `response.writeHead()`, with the headers passed
* to `response.writeHead()` given precedence.
*
* ```js
* // Returns content-type = text/plain
* const server = http.createServer((req, res) => {
* const headers = new Headers({ 'Content-Type': 'text/html' });
* res.setHeaders(headers);
* res.writeHead(200, { 'Content-Type': 'text/plain' });
* res.end('ok');
* });
* ```
*
* @since v19.6.0, v18.15.0
* @param name Header name
* @param value Header value
*/
setHeaders(headers: Headers | Map<string, number | string | readonly string[]>): this;
/**
* Append a single header value to the header object.
*
@@ -1388,6 +1451,21 @@ declare module "http" {
*/
scheduling?: "fifo" | "lifo" | undefined;
}
interface AgentGetNameOptions {
/**
* A domain name or IP address of the server to issue the request to
*/
host?: string | undefined;
/**
* Port of remote server
*/
port?: number | undefined;
/**
* Local interface to bind for network connections when issuing the request
*/
localAddress?: string | undefined;
family?: 4 | 6 | undefined;
}
/**
* An `Agent` is responsible for managing connection persistence
* and reuse for HTTP clients. It maintains a queue of pending requests
@@ -1442,12 +1520,12 @@ declare module "http" {
* });
* ```
*
* `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v22.x/api/net.html#socketconnectoptions-connectlistener) are also supported.
* `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v24.x/api/net.html#socketconnectoptions-connectlistener) are also supported.
*
* To configure any of them, a custom {@link Agent} instance must be created.
*
* ```js
* const http = require('node:http');
* import http from 'node:http';
* const keepAliveAgent = new http.Agent({ keepAlive: true });
* options.agent = keepAliveAgent;
* http.request(options, onResponseCallback)
@@ -1507,6 +1585,68 @@ declare module "http" {
* @since v0.11.4
*/
destroy(): void;
/**
* Produces a socket/stream to be used for HTTP requests.
*
* By default, this function is the same as `net.createConnection()`. However,
* custom agents may override this method in case greater flexibility is desired.
*
* A socket/stream can be supplied in one of two ways: by returning the
* socket/stream from this function, or by passing the socket/stream to `callback`.
*
* This method is guaranteed to return an instance of the `net.Socket` class,
* a subclass of `stream.Duplex`, unless the user specifies a socket
* type other than `net.Socket`.
*
* `callback` has a signature of `(err, stream)`.
* @since v0.11.4
* @param options Options containing connection details. Check `createConnection` for the format of the options
* @param callback Callback function that receives the created socket
*/
createConnection(
options: NetConnectOpts,
callback?: (err: Error | null, stream: stream.Duplex) => void,
): stream.Duplex;
/**
* Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to:
*
* ```js
* socket.setKeepAlive(true, this.keepAliveMsecs);
* socket.unref();
* return true;
* ```
*
* This method can be overridden by a particular `Agent` subclass. If this
* method returns a falsy value, the socket will be destroyed instead of persisting
* it for use with the next request.
*
* The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`.
* @since v8.1.0
*/
keepSocketAlive(socket: stream.Duplex): void;
/**
* Called when `socket` is attached to `request` after being persisted because of
* the keep-alive options. Default behavior is to:
*
* ```js
* socket.ref();
* ```
*
* This method can be overridden by a particular `Agent` subclass.
*
* The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`.
* @since v8.1.0
*/
reuseSocket(socket: stream.Duplex, request: ClientRequest): void;
/**
* Get a unique name for a set of request options, to determine whether a
* connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent,
* the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
* that determine socket reusability.
* @since v0.11.4
* @param options A set of options providing information for name generation
*/
getName(options?: AgentGetNameOptions): string;
}
const METHODS: string[];
const STATUS_CODES: {
@@ -1553,11 +1693,11 @@ declare module "http" {
*/
function createServer<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse,
>(requestListener?: RequestListener<Request, Response>): Server<Request, Response>;
function createServer<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
Response extends typeof ServerResponse<InstanceType<Request>> = typeof ServerResponse,
>(
options: ServerOptions<Request, Response>,
requestListener?: RequestListener<Request, Response>,

420
node_modules/@types/node/http2.d.ts generated vendored
View File

@@ -3,10 +3,10 @@
* It can be accessed using:
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* ```
* @since v8.4.0
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http2.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http2.js)
*/
declare module "http2" {
import EventEmitter = require("node:events");
@@ -157,7 +157,7 @@ declare module "http2" {
priority(options: StreamPriorityOptions): void;
/**
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const client = http2.connect('http://example.org:8000');
* const { NGHTTP2_CANCEL } = http2.constants;
* const req = client.request({ ':path': '/' });
@@ -177,7 +177,7 @@ declare module "http2" {
* trailers can be sent.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond(undefined, { waitForTrailers: true });
@@ -368,7 +368,7 @@ declare module "http2" {
* Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond({ ':status': 200 });
@@ -400,7 +400,7 @@ declare module "http2" {
): void;
/**
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond({ ':status': 200 });
@@ -408,15 +408,15 @@ declare module "http2" {
* });
* ```
*
* Initiates a response. 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 header fields to the peer.
* Initiates a response. 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 send trailing header fields to the peer.
*
* When `options.waitForTrailers` is set, the `Http2Stream` will not automatically
* close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond({ ':status': 200 }, { waitForTrailers: true });
@@ -439,8 +439,8 @@ declare module "http2" {
* automatically.
*
* ```js
* const http2 = require('node:http2');
* const fs = require('node:fs');
* import http2 from 'node:http2';
* import fs from 'node:fs';
*
* const server = http2.createServer();
* server.on('stream', (stream) => {
@@ -459,8 +459,8 @@ declare module "http2" {
*
* The optional `options.statCheck` function may be specified to give user code
* an opportunity to set additional content headers based on the `fs.Stat` details
* of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will perform an `fs.fstat()` call to
* collect details on the provided file descriptor.
* of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will
* perform an `fs.fstat()` call to collect details on the provided file descriptor.
*
* The `offset` and `length` options may be used to limit the response to a
* specific range subset. This can be used, for instance, to support HTTP Range
@@ -478,11 +478,12 @@ declare module "http2" {
* header fields to the peer.
*
* When `options.waitForTrailers` is set, the `Http2Stream` will not automatically
* close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`.
* close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()`
* or `http2stream.close()` to close the `Http2Stream`.
*
* ```js
* const http2 = require('node:http2');
* const fs = require('node:fs');
* import http2 from 'node:http2';
* import fs from 'node:fs';
*
* const server = http2.createServer();
* server.on('stream', (stream) => {
@@ -521,14 +522,14 @@ declare module "http2" {
* an opportunity to set additional content headers based on the `fs.Stat` details
* of the given file:
*
* If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. If the `onError` callback is
* defined, then it will be called. Otherwise
* the stream will be destroyed.
* If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an
* `RST_STREAM` frame using the standard `INTERNAL_ERROR` code.
* If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed.
*
* Example using a file path:
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* function statCheck(stat, headers) {
@@ -562,7 +563,7 @@ declare module "http2" {
* results to determine if the file has been modified to return an appropriate `304` response:
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* function statCheck(stat, headers) {
@@ -595,7 +596,7 @@ declare module "http2" {
* close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respondWithFile('/some/file',
@@ -677,7 +678,8 @@ declare module "http2" {
*/
readonly encrypted?: boolean | undefined;
/**
* A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to _this_`Http2Session` instance.
* A prototype-less object describing the current local settings of this `Http2Session`.
* The local settings are local to _this_`Http2Session` instance.
* @since v8.4.0
*/
readonly localSettings: Settings;
@@ -692,12 +694,14 @@ declare module "http2" {
readonly originSet?: string[] | undefined;
/**
* Indicates whether the `Http2Session` is currently waiting for acknowledgment of
* a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. Will be `false` once all sent `SETTINGS` frames have been acknowledged.
* a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method.
* Will be `false` once all sent `SETTINGS` frames have been acknowledged.
* @since v8.4.0
*/
readonly pendingSettingsAck: boolean;
/**
* A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer.
* A prototype-less object describing the current remote settings of this`Http2Session`.
* The remote settings are set by the _connected_ HTTP/2 peer.
* @since v8.4.0
*/
readonly remoteSettings: Settings;
@@ -801,7 +805,7 @@ declare module "http2" {
* the delta.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
*
* const server = http2.createServer();
* const expectedWindowSize = 2 ** 20;
@@ -928,7 +932,7 @@ declare module "http2" {
* This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const clientSession = http2.connect('https://localhost:1234');
* const {
* HTTP2_HEADER_PATH,
@@ -961,7 +965,10 @@ declare module "http2" {
* * `:path` \= `/`
* @since v8.4.0
*/
request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream;
request(
headers?: OutgoingHttpHeaders | readonly string[],
options?: ClientSessionRequestOptions,
): ClientHttp2Stream;
addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
addListener(event: "origin", listener: (origins: string[]) => void): this;
addListener(
@@ -1048,13 +1055,20 @@ declare module "http2" {
export interface AlternativeServiceOptions {
origin: number | string | url.URL;
}
export interface ServerHttp2Session extends Http2Session {
readonly server: Http2Server | Http2SecureServer;
export interface ServerHttp2Session<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends Http2Session {
readonly server:
| Http2Server<Http1Request, Http1Response, Http2Request, Http2Response>
| Http2SecureServer<Http1Request, Http1Response, Http2Request, Http2Response>;
/**
* Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
*
* const server = http2.createServer();
* server.on('session', (session) => {
@@ -1095,7 +1109,7 @@ declare module "http2" {
* authoritative responses.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const options = getSecureOptionsSomehow();
* const server = http2.createSecureServer(options);
* server.on('stream', (stream) => {
@@ -1121,7 +1135,7 @@ declare module "http2" {
* server using the `http2.createSecureServer()` method:
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const options = getSecureOptionsSomehow();
* options.origins = ['https://example.com', 'https://example.org'];
* const server = http2.createSecureServer(options);
@@ -1144,17 +1158,30 @@ declare module "http2" {
): void;
addListener(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
listener: (
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket,
) => void,
): this;
addListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean;
emit(
event: "connect",
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket,
): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
on(
event: "connect",
listener: (
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket,
) => void,
): this;
on(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
@@ -1162,7 +1189,10 @@ declare module "http2" {
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
listener: (
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket,
) => void,
): this;
once(
event: "stream",
@@ -1171,7 +1201,10 @@ declare module "http2" {
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
listener: (
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket,
) => void,
): this;
prependListener(
event: "stream",
@@ -1180,7 +1213,10 @@ declare module "http2" {
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
listener: (
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket,
) => void,
): this;
prependOnceListener(
event: "stream",
@@ -1190,14 +1226,66 @@ declare module "http2" {
}
// Http2Server
export interface SessionOptions {
/**
* Sets the maximum dynamic table size for deflating header fields.
* @default 4Kib
*/
maxDeflateDynamicTableSize?: number | undefined;
/**
* Sets the maximum number of settings entries per `SETTINGS` frame.
* The minimum value allowed is `1`.
* @default 32
*/
maxSettings?: number | undefined;
/**
* Sets the maximum memory that the `Http2Session` is permitted to use.
* The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte.
* The minimum value allowed is `1`.
* This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded,
* but new `Http2Stream` instances will be rejected while this limit is exceeded.
* The current number of `Http2Stream` sessions, the current memory use of the header compression tables,
* current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit.
* @default 10
*/
maxSessionMemory?: number | undefined;
/**
* Sets the maximum number of header entries.
* This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module.
* The minimum value is `1`.
* @default 128
*/
maxHeaderListPairs?: number | undefined;
/**
* Sets the maximum number of outstanding, unacknowledged pings.
* @default 10
*/
maxOutstandingPings?: number | undefined;
/**
* Sets the maximum allowed size for a serialized, compressed block of headers.
* Attempts to send headers that exceed this limit will result in
* a `'frameError'` event being emitted and the stream being closed and destroyed.
*/
maxSendHeaderBlockLength?: number | undefined;
/**
* Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.
* @default http2.constants.PADDING_STRATEGY_NONE
*/
paddingStrategy?: number | undefined;
/**
* Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received.
* Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`.
* @default 100
*/
peerMaxConcurrentStreams?: number | undefined;
/**
* The initial settings to send to the remote peer upon connection.
*/
settings?: Settings | undefined;
/**
* The array of integer values determines the settings types,
* which are included in the `CustomSettings`-property of the received remoteSettings.
* Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.
*/
remoteCustomSettings?: number[] | undefined;
/**
* Specifies a timeout in milliseconds that
@@ -1206,23 +1294,61 @@ declare module "http2" {
* @default 100000
*/
unknownProtocolTimeout?: number | undefined;
selectPadding?(frameLen: number, maxFrameLen: number): number;
}
export interface ClientSessionOptions extends SessionOptions {
/**
* Sets the maximum number of reserved push streams the client will accept at any given time.
* Once the current number of currently reserved push streams exceeds reaches this limit,
* new push streams sent by the server will be automatically rejected.
* The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1.
* A negative value sets this option to the maximum allowed value.
* @default 200
*/
maxReservedRemoteStreams?: number | undefined;
/**
* An optional callback that receives the `URL` instance passed to `connect` and the `options` object,
* and returns any `Duplex` stream that is to be used as the connection for this session.
*/
createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined;
/**
* The protocol to connect with, if not set in the `authority`.
* Value may be either `'http:'` or `'https:'`.
* @default 'https:'
*/
protocol?: "http:" | "https:" | undefined;
}
export interface ServerSessionOptions extends SessionOptions {
Http1IncomingMessage?: typeof IncomingMessage | undefined;
Http1ServerResponse?: typeof ServerResponse | undefined;
Http2ServerRequest?: typeof Http2ServerRequest | undefined;
Http2ServerResponse?: typeof Http2ServerResponse | undefined;
export interface ServerSessionOptions<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends SessionOptions {
streamResetBurst?: number | undefined;
streamResetRate?: number | undefined;
Http1IncomingMessage?: Http1Request | undefined;
Http1ServerResponse?: Http1Response | undefined;
Http2ServerRequest?: Http2Request | undefined;
Http2ServerResponse?: Http2Response | undefined;
}
export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {}
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {}
export interface ServerOptions extends ServerSessionOptions {}
export interface SecureServerOptions extends SecureServerSessionOptions {
export interface SecureServerSessionOptions<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends ServerSessionOptions<Http1Request, Http1Response, Http2Request, Http2Response>, tls.TlsOptions {}
export interface ServerOptions<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends ServerSessionOptions<Http1Request, Http1Response, Http2Request, Http2Response> {}
export interface SecureServerOptions<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends SecureServerSessionOptions<Http1Request, Http1Response, Http2Request, Http2Response> {
allowHTTP1?: boolean | undefined;
origins?: string[] | undefined;
}
@@ -1234,16 +1360,24 @@ declare module "http2" {
*/
updateSettings(settings: Settings): void;
}
export interface Http2Server extends net.Server, HTTP2ServerCommon {
export interface Http2Server<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends net.Server, HTTP2ServerCommon {
addListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
addListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
addListener(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
addListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
addListener(event: "sessionError", listener: (err: Error) => void): this;
addListener(
event: "stream",
@@ -1251,19 +1385,32 @@ declare module "http2" {
): this;
addListener(event: "timeout", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "session", session: ServerHttp2Session): boolean;
emit(
event: "checkContinue",
request: InstanceType<Http2Request>,
response: InstanceType<Http2Response>,
): boolean;
emit(event: "request", request: InstanceType<Http2Request>, response: InstanceType<Http2Response>): boolean;
emit(
event: "session",
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
): boolean;
emit(event: "sessionError", err: Error): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "timeout"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
on(
event: "request",
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
on(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
on(event: "session", listener: (session: ServerHttp2Session) => void): this;
on(event: "sessionError", listener: (err: Error) => void): this;
on(
event: "stream",
@@ -1273,10 +1420,16 @@ declare module "http2" {
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
once(
event: "request",
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
once(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
once(event: "session", listener: (session: ServerHttp2Session) => void): this;
once(event: "sessionError", listener: (err: Error) => void): this;
once(
event: "stream",
@@ -1286,13 +1439,16 @@ declare module "http2" {
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependListener(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependListener(event: "sessionError", listener: (err: Error) => void): this;
prependListener(
event: "stream",
@@ -1302,13 +1458,16 @@ declare module "http2" {
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependOnceListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependOnceListener(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
prependOnceListener(
event: "stream",
@@ -1317,16 +1476,24 @@ declare module "http2" {
prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon {
export interface Http2SecureServer<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
> extends tls.Server, HTTP2ServerCommon {
addListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
addListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
addListener(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
addListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
addListener(event: "sessionError", listener: (err: Error) => void): this;
addListener(
event: "stream",
@@ -1335,9 +1502,16 @@ declare module "http2" {
addListener(event: "timeout", listener: () => void): this;
addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "session", session: ServerHttp2Session): boolean;
emit(
event: "checkContinue",
request: InstanceType<Http2Request>,
response: InstanceType<Http2Response>,
): boolean;
emit(event: "request", request: InstanceType<Http2Request>, response: InstanceType<Http2Response>): boolean;
emit(
event: "session",
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
): boolean;
emit(event: "sessionError", err: Error): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "timeout"): boolean;
@@ -1345,10 +1519,16 @@ declare module "http2" {
emit(event: string | symbol, ...args: any[]): boolean;
on(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
on(
event: "request",
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
on(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
on(event: "session", listener: (session: ServerHttp2Session) => void): this;
on(event: "sessionError", listener: (err: Error) => void): this;
on(
event: "stream",
@@ -1359,10 +1539,16 @@ declare module "http2" {
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
once(
event: "request",
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
once(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
once(event: "session", listener: (session: ServerHttp2Session) => void): this;
once(event: "sessionError", listener: (err: Error) => void): this;
once(
event: "stream",
@@ -1373,13 +1559,16 @@ declare module "http2" {
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependListener(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependListener(event: "sessionError", listener: (err: Error) => void): this;
prependListener(
event: "stream",
@@ -1390,13 +1579,16 @@ declare module "http2" {
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependOnceListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
listener: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): this;
prependOnceListener(
event: "session",
listener: (session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>) => void,
): this;
prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
prependOnceListener(
event: "stream",
@@ -1652,7 +1844,7 @@ declare module "http2" {
* passed as the second parameter to the `'request'` event.
* @since v8.4.0
*/
export class Http2ServerResponse extends stream.Writable {
export class Http2ServerResponse<Request extends Http2ServerRequest = Http2ServerRequest> extends stream.Writable {
constructor(stream: ServerHttp2Stream);
/**
* See `response.socket`.
@@ -1668,7 +1860,7 @@ declare module "http2" {
* If there were no previous values for the header, this is equivalent to calling {@link setHeader}.
*
* Attempting to set a header field name or value that contains invalid characters will result in a
* [TypeError](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-typeerror) being thrown.
* [TypeError](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-typeerror) being thrown.
*
* ```js
* // Returns headers including "set-cookie: a" and "set-cookie: b"
@@ -1698,7 +1890,7 @@ declare module "http2" {
* A reference to the original HTTP2 `request` object.
* @since v15.7.0
*/
readonly req: Http2ServerRequest;
readonly req: Request;
/**
* Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
* applies getters, setters, and methods based on HTTP/2 logic.
@@ -1716,7 +1908,7 @@ declare module "http2" {
* All other interactions will be routed directly to the socket.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const server = http2.createServer((req, res) => {
* const ip = req.socket.remoteAddress;
* const port = req.socket.remotePort;
@@ -2292,7 +2484,7 @@ declare module "http2" {
* for use with the `HTTP2-Settings` header field.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
*
* const packed = http2.getPackedSettings({ enablePush: false });
*
@@ -2317,7 +2509,7 @@ declare module "http2" {
* with browser clients.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
*
* // Create an unencrypted HTTP/2 server.
* // Since there are no browsers known that support
@@ -2341,16 +2533,21 @@ declare module "http2" {
export function createServer(
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2Server;
export function createServer(
options: ServerOptions,
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2Server;
export function createServer<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
>(
options: ServerOptions<Http1Request, Http1Response, Http2Request, Http2Response>,
onRequestHandler?: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): Http2Server<Http1Request, Http1Response, Http2Request, Http2Response>;
/**
* Returns a `tls.Server` instance that creates and manages `Http2Session` instances.
*
* ```js
* const http2 = require('node:http2');
* const fs = require('node:fs');
* import http2 from 'node:http2';
* import fs from 'node:fs';
*
* const options = {
* key: fs.readFileSync('server-key.pem'),
@@ -2376,15 +2573,20 @@ declare module "http2" {
export function createSecureServer(
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2SecureServer;
export function createSecureServer(
options: SecureServerOptions,
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2SecureServer;
export function createSecureServer<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
>(
options: SecureServerOptions<Http1Request, Http1Response, Http2Request, Http2Response>,
onRequestHandler?: (request: InstanceType<Http2Request>, response: InstanceType<Http2Response>) => void,
): Http2SecureServer<Http1Request, Http1Response, Http2Request, Http2Response>;
/**
* Returns a `ClientHttp2Session` instance.
*
* ```js
* const http2 = require('node:http2');
* import http2 from 'node:http2';
* const client = http2.connect('https://localhost:1234');
*
* // Use the client
@@ -2411,7 +2613,15 @@ declare module "http2" {
* @param options Any `{@link createServer}` options can be provided.
* @since v20.12.0
*/
export function performServerHandshake(socket: stream.Duplex, options?: ServerOptions): ServerHttp2Session;
export function performServerHandshake<
Http1Request extends typeof IncomingMessage = typeof IncomingMessage,
Http1Response extends typeof ServerResponse<InstanceType<Http1Request>> = typeof ServerResponse,
Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest,
Http2Response extends typeof Http2ServerResponse<InstanceType<Http2Request>> = typeof Http2ServerResponse,
>(
socket: stream.Duplex,
options?: ServerOptions<Http1Request, Http1Response, Http2Request, Http2Response>,
): ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>;
}
declare module "node:http2" {
export * from "http2";

47
node_modules/@types/node/https.d.ts generated vendored
View File

@@ -1,7 +1,7 @@
/**
* HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
* separate module.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/https.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js)
*/
declare module "https" {
import { Duplex } from "node:stream";
@@ -10,18 +10,19 @@ declare module "https" {
import { URL } from "node:url";
type ServerOptions<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions<Request, Response>;
type RequestOptions =
& http.RequestOptions
& tls.SecureContextOptions
& {
checkServerIdentity?: typeof tls.checkServerIdentity | undefined;
checkServerIdentity?:
| ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined)
| undefined;
rejectUnauthorized?: boolean | undefined; // Defaults to true
servername?: string | undefined; // SNI TLS Extension
};
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
rejectUnauthorized?: boolean | undefined;
maxCachedSessions?: number | undefined;
}
/**
@@ -34,7 +35,7 @@ declare module "https" {
}
interface Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.Server<Request, Response> {}
/**
* See `http.Server` for more information.
@@ -42,7 +43,7 @@ declare module "https" {
*/
class Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends tls.Server {
constructor(requestListener?: http.RequestListener<Request, Response>);
constructor(
@@ -119,25 +120,19 @@ declare module "https" {
emit(
event: "checkContinue",
req: InstanceType<Request>,
res: InstanceType<Response> & {
req: InstanceType<Request>;
},
res: InstanceType<Response>,
): boolean;
emit(
event: "checkExpectation",
req: InstanceType<Request>,
res: InstanceType<Response> & {
req: InstanceType<Request>;
},
res: InstanceType<Response>,
): boolean;
emit(event: "clientError", err: Error, socket: Duplex): boolean;
emit(event: "connect", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
emit(
event: "request",
req: InstanceType<Request>,
res: InstanceType<Response> & {
req: InstanceType<Request>;
},
res: InstanceType<Response>,
): boolean;
emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
@@ -276,8 +271,8 @@ declare module "https" {
/**
* ```js
* // curl -k https://localhost:8000/
* const https = require('node:https');
* const fs = require('node:fs');
* import https from 'node:https';
* import fs from 'node:fs';
*
* const options = {
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
@@ -293,8 +288,8 @@ declare module "https" {
* Or
*
* ```js
* const https = require('node:https');
* const fs = require('node:fs');
* import https from 'node:https';
* import fs from 'node:fs';
*
* const options = {
* pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
@@ -312,11 +307,11 @@ declare module "https" {
*/
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
>(requestListener?: http.RequestListener<Request, Response>): Server<Request, Response>;
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
>(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
@@ -334,7 +329,7 @@ declare module "https" {
* upload a file with a POST request, then write to the `ClientRequest` object.
*
* ```js
* const https = require('node:https');
* import https from 'node:https';
*
* const options = {
* hostname: 'encrypted.google.com',
@@ -407,9 +402,9 @@ declare module "https" {
* Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`):
*
* ```js
* const tls = require('node:tls');
* const https = require('node:https');
* const crypto = require('node:crypto');
* import tls from 'node:tls';
* import https from 'node:https';
* import crypto from 'node:crypto';
*
* function sha256(s) {
* return crypto.createHash('sha256').update(s).digest('base64');
@@ -517,7 +512,7 @@ declare module "https" {
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
*
* ```js
* const https = require('node:https');
* import https from 'node:https';
*
* https.get('https://encrypted.google.com/', (res) => {
* console.log('statusCode:', res.statusCode);

22
node_modules/@types/node/index.d.ts generated vendored
View File

@@ -22,18 +22,24 @@
* IN THE SOFTWARE.
*/
// NOTE: These definitions support NodeJS and TypeScript 4.9+.
// NOTE: These definitions support Node.js and TypeScript 5.8+.
// Reference required types from the default lib:
// Reference required TypeScript libraries:
/// <reference lib="es2020" />
/// <reference lib="esnext.asynciterable" />
/// <reference lib="esnext.intl" />
/// <reference lib="esnext.bigint" />
/// <reference lib="esnext.disposable" />
/// <reference lib="esnext.float16" />
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
// Iterator definitions required for compatibility with TypeScript <5.6:
/// <reference path="compatibility/iterators.d.ts" />
// Definitions for Node.js modules specific to TypeScript 5.7+:
/// <reference path="globals.typedarray.d.ts" />
/// <reference path="buffer.buffer.d.ts" />
// Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="globals.d.ts" />
/// <reference path="assert.d.ts" />
/// <reference path="assert/strict.d.ts" />
/// <reference path="globals.d.ts" />
/// <reference path="async_hooks.d.ts" />
/// <reference path="buffer.d.ts" />
/// <reference path="child_process.d.ts" />
@@ -86,5 +92,3 @@
/// <reference path="wasi.d.ts" />
/// <reference path="worker_threads.d.ts" />
/// <reference path="zlib.d.ts" />
/// <reference path="globals.global.d.ts" />

View File

@@ -6,7 +6,7 @@
/**
* The `node:inspector` module provides an API for interacting with the V8
* inspector.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector.js)
*/
declare module 'inspector' {
import EventEmitter = require('node:events');
@@ -1703,6 +1703,146 @@ declare module 'inspector' {
message: string;
}
}
namespace Network {
/**
* Resource type as it was perceived by the rendering engine.
*/
type ResourceType = string;
/**
* Unique request identifier.
*/
type RequestId = string;
/**
* UTC time in seconds, counted from January 1, 1970.
*/
type TimeSinceEpoch = number;
/**
* 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.
*/
interface Request {
url: string;
method: string;
headers: Headers;
}
/**
* HTTP response data.
*/
interface Response {
url: string;
status: number;
statusText: string;
headers: Headers;
}
/**
* Request / response headers as keys / values of JSON object.
*/
interface Headers {
}
interface RequestWillBeSentEventDataType {
/**
* Request identifier.
*/
requestId: RequestId;
/**
* Request data.
*/
request: Request;
/**
* Request initiator.
*/
initiator: Initiator;
/**
* Timestamp.
*/
timestamp: MonotonicTime;
/**
* Timestamp.
*/
wallTime: TimeSinceEpoch;
}
interface ResponseReceivedEventDataType {
/**
* Request identifier.
*/
requestId: RequestId;
/**
* Timestamp.
*/
timestamp: MonotonicTime;
/**
* Resource type.
*/
type: ResourceType;
/**
* Response data.
*/
response: Response;
}
interface LoadingFailedEventDataType {
/**
* Request identifier.
*/
requestId: RequestId;
/**
* Timestamp.
*/
timestamp: MonotonicTime;
/**
* Resource type.
*/
type: ResourceType;
/**
* Error message.
*/
errorText: string;
}
interface LoadingFinishedEventDataType {
/**
* Request identifier.
*/
requestId: RequestId;
/**
* Timestamp.
*/
timestamp: MonotonicTime;
}
}
namespace NodeRuntime {
interface NotifyWhenWaitingForDisconnectParameterType {
enabled: boolean;
@@ -2076,6 +2216,14 @@ 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;
/**
* Disables network tracking, prevents network events from being sent to the client.
*/
post(method: 'Network.disable', callback?: (err: Error | null) => void): void;
/**
* Enables network tracking, network events will now be delivered to the client.
*/
post(method: 'Network.enable', callback?: (err: Error | null) => void): void;
/**
* Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`.
*/
@@ -2185,6 +2333,16 @@ declare module 'inspector' {
* (session ID is provided in attachedToWorker notification).
*/
addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -2224,6 +2382,10 @@ declare module 'inspector' {
emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>): boolean;
emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>): boolean;
emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>): boolean;
emit(event: 'Network.requestWillBeSent', message: InspectorNotification<Network.RequestWillBeSentEventDataType>): boolean;
emit(event: 'Network.responseReceived', message: InspectorNotification<Network.ResponseReceivedEventDataType>): boolean;
emit(event: 'Network.loadingFailed', message: InspectorNotification<Network.LoadingFailedEventDataType>): boolean;
emit(event: 'Network.loadingFinished', message: InspectorNotification<Network.LoadingFinishedEventDataType>): boolean;
emit(event: 'NodeRuntime.waitingForDisconnect'): boolean;
emit(event: 'NodeRuntime.waitingForDebugger'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
@@ -2321,6 +2483,16 @@ declare module 'inspector' {
* (session ID is provided in attachedToWorker notification).
*/
on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
on(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
on(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
on(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -2428,6 +2600,16 @@ declare module 'inspector' {
* (session ID is provided in attachedToWorker notification).
*/
once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
once(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
once(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
once(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -2535,6 +2717,16 @@ declare module 'inspector' {
* (session ID is provided in attachedToWorker notification).
*/
prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -2642,6 +2834,16 @@ declare module 'inspector' {
* (session ID is provided in attachedToWorker notification).
*/
prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -2663,7 +2865,7 @@ declare module 'inspector' {
* If wait is `true`, will block until a client has connected to the inspect port
* and flow control has been passed to the debugger client.
*
* See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
* See the [security warning](https://nodejs.org/docs/latest-v24.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
* regarding the `host` parameter usage.
* @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI.
* @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI.
@@ -2737,6 +2939,42 @@ declare module 'inspector' {
* @since v11.0.0
*/
const console: InspectorConsole;
// DevTools protocol event broadcast methods
namespace Network {
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that
* the application is about to send an HTTP request.
* @since v22.6.0
*/
function requestWillBeSent(params: RequestWillBeSentEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that
* HTTP response is available.
* @since v22.6.0
*/
function responseReceived(params: ResponseReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that
* HTTP request has finished loading.
* @since v22.6.0
*/
function loadingFinished(params: LoadingFinishedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that
* HTTP request has failed to load.
* @since v22.7.0
*/
function loadingFailed(params: LoadingFailedEventDataType): void;
}
}
/**
@@ -2750,7 +2988,7 @@ declare module 'node:inspector' {
/**
* The `node:inspector/promises` module provides an API for interacting with the V8
* inspector.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector/promises.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector/promises.js)
* @since v19.0.0
*/
declare module 'inspector/promises' {
@@ -2770,6 +3008,7 @@ declare module 'inspector/promises' {
HeapProfiler,
NodeTracing,
NodeWorker,
Network,
NodeRuntime,
} from 'inspector';
@@ -3087,6 +3326,14 @@ declare module 'inspector/promises' {
* Detached from the worker with given sessionId.
*/
post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise<void>;
/**
* Disables network tracking, prevents network events from being sent to the client.
*/
post(method: 'Network.disable'): Promise<void>;
/**
* Enables network tracking, network events will now be delivered to the client.
*/
post(method: 'Network.enable'): Promise<void>;
/**
* Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`.
*/
@@ -3195,6 +3442,16 @@ declare module 'inspector/promises' {
* (session ID is provided in attachedToWorker notification).
*/
addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -3234,6 +3491,10 @@ declare module 'inspector/promises' {
emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>): boolean;
emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>): boolean;
emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>): boolean;
emit(event: 'Network.requestWillBeSent', message: InspectorNotification<Network.RequestWillBeSentEventDataType>): boolean;
emit(event: 'Network.responseReceived', message: InspectorNotification<Network.ResponseReceivedEventDataType>): boolean;
emit(event: 'Network.loadingFailed', message: InspectorNotification<Network.LoadingFailedEventDataType>): boolean;
emit(event: 'Network.loadingFinished', message: InspectorNotification<Network.LoadingFinishedEventDataType>): boolean;
emit(event: 'NodeRuntime.waitingForDisconnect'): boolean;
emit(event: 'NodeRuntime.waitingForDebugger'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
@@ -3331,6 +3592,16 @@ declare module 'inspector/promises' {
* (session ID is provided in attachedToWorker notification).
*/
on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
on(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
on(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
on(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -3438,6 +3709,16 @@ declare module 'inspector/promises' {
* (session ID is provided in attachedToWorker notification).
*/
once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
once(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
once(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
once(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -3545,6 +3826,16 @@ declare module 'inspector/promises' {
* (session ID is provided in attachedToWorker notification).
*/
prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -3652,6 +3943,16 @@ declare module 'inspector/promises' {
* (session ID is provided in attachedToWorker notification).
*/
prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this;
/**
* Fired when page is about to send HTTP request.
*/
prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification<Network.RequestWillBeSentEventDataType>) => void): this;
/**
* Fired when HTTP response is available.
*/
prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification<Network.ResponseReceivedEventDataType>) => void): this;
prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification<Network.LoadingFailedEventDataType>) => void): this;
prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification<Network.LoadingFinishedEventDataType>) => void): this;
/**
* This event is fired instead of `Runtime.executionContextDestroyed` when
* enabled.
@@ -3682,6 +3983,7 @@ declare module 'inspector/promises' {
HeapProfiler,
NodeTracing,
NodeWorker,
Network,
NodeRuntime,
};
}

886
node_modules/@types/node/module.d.ts generated vendored
View File

@@ -1,20 +1,334 @@
/**
* @since v0.3.7
* @experimental
*/
declare module "module" {
import { URL } from "node:url";
import { MessagePort } from "node:worker_threads";
class Module {
constructor(id: string, parent?: Module);
}
interface Module extends NodeJS.Module {}
namespace Module {
export { Module };
}
namespace Module {
/**
* A list of the names of all modules provided by Node.js. Can be used to verify
* if a module is maintained by a third party or not.
*
* Note: the list doesn't contain prefix-only modules like `node:test`.
* @since v9.3.0, v8.10.0, v6.13.0
*/
const builtinModules: readonly string[];
/**
* @since v12.2.0
* @param path Filename to be used to construct the require
* function. Must be a file URL object, file URL string, or absolute path
* string.
*/
function createRequire(path: string | URL): NodeJS.Require;
namespace constants {
/**
* The following constants are returned as the `status` field in the object returned by
* {@link enableCompileCache} to indicate the result of the attempt to enable the
* [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache).
* @since v22.8.0
*/
namespace compileCacheStatus {
/**
* Node.js has enabled the compile cache successfully. The directory used to store the
* compile cache will be returned in the `directory` field in the
* returned object.
*/
const ENABLED: number;
/**
* The compile cache has already been enabled before, either by a previous call to
* {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir`
* environment variable. The directory used to store the
* compile cache will be returned in the `directory` field in the
* returned object.
*/
const ALREADY_ENABLED: number;
/**
* Node.js fails to enable the compile cache. This can be caused by the lack of
* permission to use the specified directory, or various kinds of file system errors.
* The detail of the failure will be returned in the `message` field in the
* returned object.
*/
const FAILED: number;
/**
* Node.js cannot enable the compile cache because the environment variable
* `NODE_DISABLE_COMPILE_CACHE=1` has been set.
*/
const DISABLED: number;
}
}
interface EnableCompileCacheResult {
/**
* One of the {@link constants.compileCacheStatus}
*/
status: number;
/**
* If Node.js cannot enable the compile cache, this contains
* the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`.
*/
message?: string;
/**
* If the compile cache is enabled, this contains the directory
* where the compile cache is stored. Only set if `status` is
* `module.constants.compileCacheStatus.ENABLED` or
* `module.constants.compileCacheStatus.ALREADY_ENABLED`.
*/
directory?: string;
}
/**
* Enable [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache)
* in the current Node.js instance.
*
* If `cacheDir` is not specified, Node.js will either use the directory specified by the
* `NODE_COMPILE_CACHE=dir` environment variable if it's set, or use
* `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. For general use cases, it's
* recommended to call `module.enableCompileCache()` without specifying the `cacheDir`,
* so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment
* variable when necessary.
*
* Since compile cache is supposed to be a quiet optimization that is not required for the
* application to be functional, this method is designed to not throw any exception when the
* compile cache cannot be enabled. Instead, it will return an object containing an error
* message in the `message` field to aid debugging.
* If compile cache is enabled successfully, the `directory` field in the returned object
* contains the path to the directory where the compile cache is stored. The `status`
* field in the returned object would be one of the `module.constants.compileCacheStatus`
* values to indicate the result of the attempt to enable the
* [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache).
*
* This method only affects the current Node.js instance. To enable it in child worker threads,
* either call this method in child worker threads too, or set the
* `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can
* be inherited into the child workers. The directory can be obtained either from the
* `directory` field returned by this method, or with {@link getCompileCacheDir}.
* @since v22.8.0
* @param cacheDir Optional path to specify the directory where the compile cache
* will be stored/retrieved.
*/
function enableCompileCache(cacheDir?: string): EnableCompileCacheResult;
/**
* Flush the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache)
* accumulated from modules already loaded
* in the current Node.js instance to disk. This returns after all the flushing
* file system operations come to an end, no matter they succeed or not. If there
* are any errors, this will fail silently, since compile cache misses should not
* interfere with the actual operation of the application.
* @since v22.10.0
*/
function flushCompileCache(): void;
/**
* @since v22.8.0
* @return Path to the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache)
* directory if it is enabled, or `undefined` otherwise.
*/
function getCompileCacheDir(): string | undefined;
/**
* ```text
* /path/to/project
* ├ packages/
* ├ bar/
* ├ bar.js
* └ package.json // name = '@foo/bar'
* └ qux/
* ├ node_modules/
* └ some-package/
* └ package.json // name = 'some-package'
* ├ qux.js
* └ package.json // name = '@foo/qux'
* ├ main.js
* └ package.json // name = '@foo'
* ```
* ```js
* // /path/to/project/packages/bar/bar.js
* import { findPackageJSON } from 'node:module';
*
* findPackageJSON('..', import.meta.url);
* // '/path/to/project/package.json'
* // Same result when passing an absolute specifier instead:
* findPackageJSON(new URL('../', import.meta.url));
* findPackageJSON(import.meta.resolve('../'));
*
* findPackageJSON('some-package', import.meta.url);
* // '/path/to/project/packages/bar/node_modules/some-package/package.json'
* // When passing an absolute specifier, you might get a different result if the
* // resolved module is inside a subfolder that has nested `package.json`.
* findPackageJSON(import.meta.resolve('some-package'));
* // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'
*
* findPackageJSON('@foo/qux', import.meta.url);
* // '/path/to/project/packages/qux/package.json'
* ```
* @since v22.14.0
* @param specifier The specifier for the module whose `package.json` to
* retrieve. When passing a _bare specifier_, the `package.json` at the root of
* the package is returned. When passing a _relative specifier_ or an _absolute specifier_,
* the closest parent `package.json` is returned.
* @param base The absolute location (`file:` URL string or FS path) of the
* containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use
* `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_.
* @returns A path if the `package.json` is found. When `startLocation`
* is a package, the package's root `package.json`; when a relative or unresolved, the closest
* `package.json` to the `startLocation`.
*/
function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined;
/**
* @since v18.6.0, v16.17.0
*/
function isBuiltin(moduleName: string): boolean;
interface RegisterOptions<Data> {
/**
* If you want to resolve `specifier` relative to a
* base URL, such as `import.meta.url`, you can pass that URL here. This
* property is ignored if the `parentURL` is supplied as the second argument.
* @default 'data:'
*/
parentURL?: string | URL | undefined;
/**
* Any arbitrary, cloneable JavaScript value to pass into the
* {@link initialize} hook.
*/
data?: Data | undefined;
/**
* [Transferable objects](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#portpostmessagevalue-transferlist)
* to be passed into the `initialize` hook.
*/
transferList?: any[] | undefined;
}
/* eslint-disable @definitelytyped/no-unnecessary-generics */
/**
* Register a module that exports hooks that customize Node.js module
* resolution and loading behavior. See
* [Customization hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks).
*
* 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
* @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`.
* @param parentURL f you want to resolve `specifier` relative to a base
* URL, such as `import.meta.url`, you can pass that URL here.
*/
function register<Data = any>(
specifier: string | URL,
parentURL?: string | URL,
options?: RegisterOptions<Data>,
): void;
function register<Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void;
interface RegisterHooksOptions {
/**
* See [load hook](https://nodejs.org/docs/latest-v24.x/api/module.html#loadurl-context-nextload).
* @default undefined
*/
load?: LoadHookSync | undefined;
/**
* See [resolve hook](https://nodejs.org/docs/latest-v24.x/api/module.html#resolvespecifier-context-nextresolve).
* @default undefined
*/
resolve?: ResolveHookSync | undefined;
}
interface ModuleHooks {
/**
* Deregister the hook instance.
*/
deregister(): void;
}
/**
* Register [hooks](https://nodejs.org/docs/latest-v24.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:
* * `'strip'` Only strip type annotations without performing the transformation of TypeScript features.
* * `'transform'` Strip type annotations and transform TypeScript features to JavaScript.
* @default 'strip'
*/
mode?: "strip" | "transform" | undefined;
/**
* Only when `mode` is `'transform'`, if `true`, a source map
* will be generated for the transformed code.
* @default false
*/
sourceMap?: boolean | undefined;
/**
* Specifies the source url used in the source map.
*/
sourceUrl?: string | undefined;
}
/**
* `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It
* can be used to strip type annotations from TypeScript code before running it
* with `vm.runInContext()` or `vm.compileFunction()`.
* By default, it will throw an error if the code contains TypeScript features
* that require transformation such as `Enums`,
* see [type-stripping](https://nodejs.org/docs/latest-v24.x/api/typescript.md#type-stripping) for more information.
* When mode is `'transform'`, it also transforms TypeScript features to JavaScript,
* see [transform TypeScript features](https://nodejs.org/docs/latest-v24.x/api/typescript.md#typescript-features) for more information.
* When mode is `'strip'`, source maps are not generated, because locations are preserved.
* If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown.
*
* _WARNING_: The output of this function should not be considered stable across Node.js versions,
* due to changes in the TypeScript parser.
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = 'const a: number = 1;';
* const strippedCode = stripTypeScriptTypes(code);
* console.log(strippedCode);
* // Prints: const a = 1;
* ```
*
* If `sourceUrl` is provided, it will be used appended as a comment at the end of the output:
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = 'const a: number = 1;';
* const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
* console.log(strippedCode);
* // Prints: const a = 1\n\n//# sourceURL=source.ts;
* ```
*
* When `mode` is `'transform'`, the code is transformed to JavaScript:
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = `
* namespace MathUtil {
* export const add = (a: number, b: number) => a + b;
* }`;
* const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
* console.log(strippedCode);
* // Prints:
* // var MathUtil;
* // (function(MathUtil) {
* // MathUtil.add = (a, b)=>a + b;
* // })(MathUtil || (MathUtil = {}));
* // # sourceMappingURL=data:application/json;base64, ...
* ```
* @since v22.13.0
* @param code The code to strip type annotations from.
* @returns The code with type annotations stripped.
*/
function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string;
/* eslint-enable @definitelytyped/no-unnecessary-generics */
/**
* The `module.syncBuiltinESMExports()` method updates all the live bindings for
* builtin `ES Modules` to match the properties of the `CommonJS` exports. It
* does not add or remove exported names from the `ES Modules`.
*
* ```js
* const fs = require('node:fs');
* const assert = require('node:assert');
* const { syncBuiltinESMExports } = require('node:module');
* import fs from 'node:fs';
* import assert from 'node:assert';
* import { syncBuiltinESMExports } from 'node:module';
*
* fs.readFile = newAPI;
*
@@ -42,13 +356,195 @@ declare module "module" {
* @since v12.12.0
*/
function syncBuiltinESMExports(): void;
interface ImportAttributes extends NodeJS.Dict<string> {
type?: string | undefined;
}
type ModuleFormat =
| "addon"
| "builtin"
| "commonjs"
| "commonjs-typescript"
| "json"
| "module"
| "module-typescript"
| "wasm";
type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray;
/**
* The `initialize` hook provides a way to define a custom function that runs in
* the hooks thread when the hooks module is initialized. Initialization happens
* when the hooks module is registered via {@link register}.
*
* This hook can receive data from a {@link register} invocation, including
* ports and other transferable objects. The return value of `initialize` can be a
* `Promise`, in which case it will be awaited before the main application thread
* execution resumes.
*/
type InitializeHook<Data = any> = (data: Data) => void | Promise<void>;
interface ResolveHookContext {
/**
* Export conditions of the relevant `package.json`
*/
conditions: string[];
/**
* An object whose key-value pairs represent the assertions for the module to import
*/
importAttributes: ImportAttributes;
/**
* The module importing this one, or undefined if this is the Node.js entry point
*/
parentURL: string | undefined;
}
interface ResolveFnOutput {
/**
* A hint to the load hook (it might be ignored); can be an intermediary value.
*/
format?: string | null | undefined;
/**
* The import attributes to use when caching the module (optional; if excluded the input will be used)
*/
importAttributes?: ImportAttributes | undefined;
/**
* A signal that this hook intends to terminate the chain of `resolve` hooks.
* @default false
*/
shortCircuit?: boolean | undefined;
/**
* The absolute URL to which this input resolves
*/
url: string;
}
/**
* The `resolve` hook chain is responsible for telling Node.js where to find and
* how to cache a given `import` statement or expression, or `require` call. It can
* optionally return a format (such as `'module'`) as a hint to the `load` hook. If
* a format is specified, the `load` hook is ultimately responsible for providing
* the final `format` value (and it is free to ignore the hint provided by
* `resolve`); if `resolve` provides a `format`, a custom `load` hook is required
* even if only to pass the value to the Node.js default `load` hook.
*/
type ResolveHook = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: Partial<ResolveHookContext>,
) => ResolveFnOutput | Promise<ResolveFnOutput>,
) => ResolveFnOutput | Promise<ResolveFnOutput>;
type ResolveHookSync = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: Partial<ResolveHookContext>,
) => ResolveFnOutput,
) => ResolveFnOutput;
interface LoadHookContext {
/**
* Export conditions of the relevant `package.json`
*/
conditions: string[];
/**
* The format optionally supplied by the `resolve` hook chain (can be an intermediary value).
*/
format: string | null | undefined;
/**
* An object whose key-value pairs represent the assertions for the module to import
*/
importAttributes: ImportAttributes;
}
interface LoadFnOutput {
format: string | null | undefined;
/**
* A signal that this hook intends to terminate the chain of `resolve` hooks.
* @default false
*/
shortCircuit?: boolean | undefined;
/**
* The source for Node.js to evaluate
*/
source?: ModuleSource | undefined;
}
/**
* The `load` hook provides a way to define a custom method of determining how a
* URL should be interpreted, retrieved, and parsed. It is also in charge of
* validating the import attributes.
*/
type LoadHook = (
url: string,
context: LoadHookContext,
nextLoad: (
url: string,
context?: Partial<LoadHookContext>,
) => LoadFnOutput | Promise<LoadFnOutput>,
) => LoadFnOutput | Promise<LoadFnOutput>;
type LoadHookSync = (
url: string,
context: LoadHookContext,
nextLoad: (
url: string,
context?: Partial<LoadHookContext>,
) => LoadFnOutput,
) => LoadFnOutput;
interface SourceMapsSupport {
/**
* If the source maps support is enabled
*/
enabled: boolean;
/**
* If the support is enabled for files in `node_modules`.
*/
nodeModules: boolean;
/**
* If the support is enabled for generated code from `eval` or `new Function`.
*/
generatedCode: boolean;
}
/**
* This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack
* traces is enabled.
* @since v23.7.0, v22.14.0
*/
function getSourceMapsSupport(): SourceMapsSupport;
/**
* `path` is the resolved path for the file for which a corresponding source map
* should be fetched.
* @since v13.7.0, v12.17.0
* @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise.
*/
function findSourceMap(path: string, error?: Error): SourceMap;
function findSourceMap(path: string): SourceMap | undefined;
interface SetSourceMapsSupportOptions {
/**
* If enabling the support for files in `node_modules`.
* @default false
*/
nodeModules?: boolean | undefined;
/**
* If enabling the support for generated code from `eval` or `new Function`.
* @default false
*/
generatedCode?: boolean | undefined;
}
/**
* This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for
* stack traces.
*
* It provides same features as launching Node.js process with commandline options
* `--enable-source-maps`, with additional options to alter the support for files
* in `node_modules` or generated codes.
*
* Only source maps in JavaScript files that are loaded after source maps has been
* enabled will be parsed and loaded. Preferably, use the commandline options
* `--enable-source-maps` to avoid losing track of source maps of modules loaded
* before this API call.
* @since v23.7.0, v22.14.0
*/
function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void;
interface SourceMapConstructorOptions {
/**
* @since v21.0.0, v20.5.0
*/
lineLengths?: readonly number[] | undefined;
}
interface SourceMapPayload {
file: string;
version: number;
@@ -69,7 +565,7 @@ declare module "module" {
/**
* The name of the range in the source map, if one was provided
*/
name?: string;
name: string | undefined;
/**
* The file name of the original source, as reported in the SourceMap
*/
@@ -87,11 +583,11 @@ declare module "module" {
* @since v13.7.0, v12.17.0
*/
class SourceMap {
constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions);
/**
* Getter for the payload used to construct the `SourceMap` instance.
*/
readonly payload: SourceMapPayload;
constructor(payload: SourceMapPayload);
/**
* Given a line offset and column offset in the generated source
* file, returns an object representing the SourceMap range in the
@@ -110,7 +606,7 @@ declare module "module" {
* @param lineOffset The zero-indexed line number offset in the generated source
* @param columnOffset The zero-indexed column number offset in the generated source
*/
findEntry(lineOffset: number, columnOffset: number): SourceMapping;
findEntry(lineOffset: number, columnOffset: number): SourceMapping | {};
/**
* Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source,
* find the corresponding call site location in the original source.
@@ -122,176 +618,248 @@ declare module "module" {
*/
findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {};
}
interface ImportAttributes extends NodeJS.Dict<string> {
type?: string | undefined;
}
type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm";
type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray;
interface GlobalPreloadContext {
port: MessagePort;
}
/**
* @deprecated This hook will be removed in a future version.
* Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored.
*
* Sometimes it might be necessary to run some code inside of the same global scope that the application runs in.
* This hook allows the return of a string that is run as a sloppy-mode script on startup.
*
* @param context Information to assist the preload code
* @return Code to run before application startup
*/
type GlobalPreloadHook = (context: GlobalPreloadContext) => string;
/**
* The `initialize` hook provides a way to define a custom function that runs in the hooks thread
* when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`.
*
* This hook can receive data from a `register` invocation, including ports and other transferrable objects.
* The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes.
*/
type InitializeHook<Data = any> = (data: Data) => void | Promise<void>;
interface ResolveHookContext {
/**
* Export conditions of the relevant `package.json`
*/
conditions: string[];
/**
* An object whose key-value pairs represent the assertions for the module to import
*/
importAttributes: ImportAttributes;
/**
* The module importing this one, or undefined if this is the Node.js entry point
*/
parentURL: string | undefined;
}
interface ResolveFnOutput {
/**
* A hint to the load hook (it might be ignored)
*/
format?: ModuleFormat | null | undefined;
/**
* The import attributes to use when caching the module (optional; if excluded the input will be used)
*/
importAttributes?: ImportAttributes | undefined;
/**
* A signal that this hook intends to terminate the chain of `resolve` hooks.
* @default false
*/
shortCircuit?: boolean | undefined;
/**
* The absolute URL to which this input resolves
*/
url: string;
}
/**
* The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook.
* If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`);
* if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook.
*
* @param specifier The specified URL path of the module to be resolved
* @param context
* @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook
*/
type ResolveHook = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: ResolveHookContext,
) => ResolveFnOutput | Promise<ResolveFnOutput>,
) => ResolveFnOutput | Promise<ResolveFnOutput>;
interface LoadHookContext {
/**
* Export conditions of the relevant `package.json`
*/
conditions: string[];
/**
* The format optionally supplied by the `resolve` hook chain
*/
format: ModuleFormat;
/**
* An object whose key-value pairs represent the assertions for the module to import
*/
importAttributes: ImportAttributes;
}
interface LoadFnOutput {
format: ModuleFormat;
/**
* A signal that this hook intends to terminate the chain of `resolve` hooks.
* @default false
*/
shortCircuit?: boolean | undefined;
/**
* The source for Node.js to evaluate
*/
source?: ModuleSource;
}
/**
* The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed.
* It is also in charge of validating the import assertion.
*
* @param url The URL/path of the module to be loaded
* @param context Metadata about the module
* @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook
*/
type LoadHook = (
url: string,
context: LoadHookContext,
nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise<LoadFnOutput>,
) => LoadFnOutput | Promise<LoadFnOutput>;
}
interface RegisterOptions<Data> {
parentURL: string | URL;
data?: Data | undefined;
transferList?: any[] | undefined;
}
interface Module extends NodeModule {}
class Module {
static runMain(): void;
static wrap(code: string): string;
static createRequire(path: string | URL): NodeRequire;
static builtinModules: string[];
static isBuiltin(moduleName: string): boolean;
static Module: typeof Module;
static register<Data = any>(
specifier: string | URL,
parentURL?: string | URL,
options?: RegisterOptions<Data>,
): void;
static register<Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void;
constructor(id: string, parent?: Module);
function runMain(main?: string): void;
function wrap(script: string): string;
}
global {
interface ImportMeta {
/**
* The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`.
* **Caveat:** only present on `file:` modules.
* The directory name of the current module.
*
* This is the same as the `path.dirname()` of the `import.meta.filename`.
*
* > **Caveat**: only present on `file:` modules.
* @since v21.2.0, v20.11.0
*/
dirname: string;
/**
* The full absolute path and filename of the current module, with symlinks resolved.
* The full absolute path and filename of the current module, with
* symlinks resolved.
*
* This is the same as the `url.fileURLToPath()` of the `import.meta.url`.
* **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it.
*
* > **Caveat** only local modules support this property. Modules not using the
* > `file:` protocol will not provide it.
* @since v21.2.0, v20.11.0
*/
filename: string;
/**
* The absolute `file:` URL of the module.
*
* This is defined exactly the same as it is in browsers providing the URL of the
* current module file.
*
* This enables useful patterns such as relative file loading:
*
* ```js
* import { readFileSync } from 'node:fs';
* const buffer = readFileSync(new URL('./data.proto', import.meta.url));
* ```
*/
url: string;
/**
* Provides a module-relative resolution function scoped to each module, returning
* the URL string.
* `import.meta.resolve` is a module-relative resolution function scoped to
* each module, returning the URL string.
*
* Second `parent` parameter is only used when the `--experimental-import-meta-resolve`
* command flag enabled.
* ```js
* const dependencyAsset = import.meta.resolve('component-lib/asset.css');
* // file:///app/node_modules/component-lib/asset.css
* import.meta.resolve('./dep.js');
* // file:///app/dep.js
* ```
*
* @since v20.6.0
* All features of the Node.js module resolution are supported. Dependency
* resolutions are subject to the permitted exports resolutions within the package.
*
* @param specifier The module specifier to resolve relative to `parent`.
* @param parent The absolute parent module URL to resolve from.
* @returns The absolute (`file:`) URL string for the resolved module.
* **Caveats**:
*
* * This can result in synchronous file-system operations, which
* can impact performance similarly to `require.resolve`.
* * This feature is not available within custom loaders (it would
* create a deadlock).
* @since v13.9.0, v12.16.0
* @param specifier The module specifier to resolve relative to the
* current module.
* @param parent An optional absolute parent module URL to resolve from.
* **Default:** `import.meta.url`
* @returns The absolute URL string that the specifier would resolve to.
*/
resolve(specifier: string, parent?: string | URL | undefined): string;
resolve(specifier: string, parent?: string | URL): string;
}
namespace NodeJS {
interface Module {
/**
* The module objects required for the first time by this one.
* @since v0.1.16
*/
children: Module[];
/**
* The `module.exports` object is created by the `Module` system. Sometimes this is
* not acceptable; many want their module to be an instance of some class. To do
* this, assign the desired export object to `module.exports`.
* @since v0.1.16
*/
exports: any;
/**
* The fully resolved filename of the module.
* @since v0.1.16
*/
filename: string;
/**
* The identifier for the module. Typically this is the fully resolved
* filename.
* @since v0.1.16
*/
id: string;
/**
* `true` if the module is running during the Node.js preload
* phase.
* @since v15.4.0, v14.17.0
*/
isPreloading: boolean;
/**
* Whether or not the module is done loading, or is in the process of
* loading.
* @since v0.1.16
*/
loaded: boolean;
/**
* The module that first required this one, or `null` if the current module is the
* entry point of the current process, or `undefined` if the module was loaded by
* something that is not a CommonJS module (e.g. REPL or `import`).
* @since v0.1.16
* @deprecated Please use `require.main` and `module.children` instead.
*/
parent: Module | null | undefined;
/**
* The directory name of the module. This is usually the same as the
* `path.dirname()` of the `module.id`.
* @since v11.14.0
*/
path: string;
/**
* The search paths for the module.
* @since v0.4.0
*/
paths: string[];
/**
* The `module.require()` method provides a way to load a module as if
* `require()` was called from the original module.
* @since v0.5.1
*/
require(id: string): any;
}
interface Require {
/**
* Used to import modules, `JSON`, and local files.
* @since v0.1.13
*/
(id: string): any;
/**
* Modules are cached in this object when they are required. By deleting a key
* value from this object, the next `require` will reload the module.
* This does not apply to
* [native addons](https://nodejs.org/docs/latest-v24.x/api/addons.html),
* for which reloading will result in an error.
* @since v0.3.0
*/
cache: Dict<Module>;
/**
* Instruct `require` on how to handle certain file extensions.
* @since v0.3.0
* @deprecated
*/
extensions: RequireExtensions;
/**
* The `Module` object representing the entry script loaded when the Node.js
* process launched, or `undefined` if the entry point of the program is not a
* CommonJS module.
* @since v0.1.17
*/
main: Module | undefined;
/**
* @since v0.3.0
*/
resolve: RequireResolve;
}
/** @deprecated */
interface RequireExtensions extends Dict<(module: Module, filename: string) => any> {
".js": (module: Module, filename: string) => any;
".json": (module: Module, filename: string) => any;
".node": (module: Module, filename: string) => any;
}
interface RequireResolveOptions {
/**
* Paths to resolve module location from. If present, these
* paths are used instead of the default resolution paths, with the exception
* of
* [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v24.x/api/modules.html#loading-from-the-global-folders)
* like `$HOME/.node_modules`, which are
* always included. Each of these paths is used as a starting point for
* the module resolution algorithm, meaning that the `node_modules` hierarchy
* is checked from this location.
* @since v8.9.0
*/
paths?: string[] | undefined;
}
interface RequireResolve {
/**
* Use the internal `require()` machinery to look up the location of a module,
* but rather than loading the module, just return the resolved filename.
*
* If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
* @since v0.3.0
* @param request The module path to resolve.
*/
(request: string, options?: RequireResolveOptions): string;
/**
* Returns an array containing the paths searched during resolution of `request` or
* `null` if the `request` string references a core module, for example `http` or
* `fs`.
* @since v8.9.0
* @param request The module path whose lookup paths are being retrieved.
*/
paths(request: string): string[] | null;
}
}
/**
* The directory name of the current module. This is the same as the
* `path.dirname()` of the `__filename`.
* @since v0.1.27
*/
var __dirname: string;
/**
* The file name of the current module. This is the current module file's absolute
* path with symlinks resolved.
*
* For a main program this is not necessarily the same as the file name used in the
* command line.
* @since v0.0.1
*/
var __filename: string;
/**
* The `exports` variable is available within a module's file-level scope, and is
* assigned the value of `module.exports` before the module is evaluated.
* @since v0.1.16
*/
var exports: NodeJS.Module["exports"];
/**
* A reference to the current module.
* @since v0.1.16
*/
var module: NodeJS.Module;
/**
* @since v0.1.13
*/
var require: NodeJS.Require;
// Global-scope aliases for backwards compatibility with @types/node <13.0.x
// TODO: consider removing in a future major version update
/** @deprecated Use `NodeJS.Module` instead. */
interface NodeModule extends NodeJS.Module {}
/** @deprecated Use `NodeJS.Require` instead. */
interface NodeRequire extends NodeJS.Require {}
/** @deprecated Use `NodeJS.RequireResolve` instead. */
interface RequireResolve extends NodeJS.RequireResolve {}
}
export = Module;
}

93
node_modules/@types/node/net.d.ts generated vendored
View File

@@ -8,9 +8,9 @@
* It can be accessed using:
*
* ```js
* const net = require('node:net');
* import net from 'node:net';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/net.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/net.js)
*/
declare module "net" {
import * as stream from "node:stream";
@@ -29,6 +29,7 @@ declare module "net" {
interface SocketConstructorOpts {
fd?: number | undefined;
allowHalfOpen?: boolean | undefined;
onread?: OnReadOpts | undefined;
readable?: boolean | undefined;
writable?: boolean | undefined;
signal?: AbortSignal;
@@ -37,20 +38,12 @@ declare module "net" {
buffer: Uint8Array | (() => Uint8Array);
/**
* This function is called for every chunk of incoming data.
* Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer.
* Return false from this function to implicitly pause() the socket.
* Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`.
* Return `false` from this function to implicitly `pause()` the socket.
*/
callback(bytesWritten: number, buf: Uint8Array): boolean;
callback(bytesWritten: number, buffer: Uint8Array): boolean;
}
interface ConnectOpts {
/**
* If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
* Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
* still be emitted as normal and methods like pause() and resume() will also behave as expected.
*/
onread?: OnReadOpts | undefined;
}
interface TcpSocketConnectOpts extends ConnectOpts {
interface TcpSocketConnectOpts {
port: number;
host?: string | undefined;
localAddress?: string | undefined;
@@ -69,8 +62,9 @@ declare module "net" {
* @since v18.13.0
*/
autoSelectFamilyAttemptTimeout?: number | undefined;
blockList?: BlockList | undefined;
}
interface IpcSocketConnectOpts extends ConnectOpts {
interface IpcSocketConnectOpts {
path: string;
}
type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts;
@@ -112,8 +106,8 @@ declare module "net" {
* @since v0.1.90
* @param [encoding='utf8'] Only used when data is `string`.
*/
write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean;
write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean;
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
/**
* Initiate a connection on a given socket.
*
@@ -380,7 +374,7 @@ declare module "net" {
addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
addListener(
event: "connectionAttemptFailed",
listener: (ip: string, port: number, family: number) => void,
listener: (ip: string, port: number, family: number, error: Error) => void,
): this;
addListener(
event: "connectionAttemptTimeout",
@@ -400,7 +394,7 @@ declare module "net" {
emit(event: "close", hadError: boolean): boolean;
emit(event: "connect"): boolean;
emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean;
emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean;
emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean;
emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean;
emit(event: "data", data: Buffer): boolean;
emit(event: "drain"): boolean;
@@ -413,7 +407,10 @@ declare module "net" {
on(event: "close", listener: (hadError: boolean) => void): this;
on(event: "connect", listener: () => void): this;
on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this;
on(
event: "connectionAttemptFailed",
listener: (ip: string, port: number, family: number, error: Error) => void,
): this;
on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
on(event: "data", listener: (data: Buffer) => void): this;
on(event: "drain", listener: () => void): this;
@@ -428,7 +425,10 @@ declare module "net" {
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: (hadError: boolean) => void): this;
once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this;
once(
event: "connectionAttemptFailed",
listener: (ip: string, port: number, family: number, error: Error) => void,
): this;
once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
once(event: "connect", listener: () => void): this;
once(event: "data", listener: (data: Buffer) => void): this;
@@ -447,7 +447,7 @@ declare module "net" {
prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this;
prependListener(
event: "connectionAttemptFailed",
listener: (ip: string, port: number, family: number) => void,
listener: (ip: string, port: number, family: number, error: Error) => void,
): this;
prependListener(
event: "connectionAttemptTimeout",
@@ -472,7 +472,7 @@ declare module "net" {
): this;
prependOnceListener(
event: "connectionAttemptFailed",
listener: (ip: string, port: number, family: number) => void,
listener: (ip: string, port: number, family: number, error: Error) => void,
): this;
prependOnceListener(
event: "connectionAttemptTimeout",
@@ -490,17 +490,18 @@ declare module "net" {
prependOnceListener(event: "timeout", listener: () => void): this;
}
interface ListenOptions extends Abortable {
port?: number | undefined;
host?: string | undefined;
backlog?: number | undefined;
path?: string | undefined;
exclusive?: boolean | undefined;
readableAll?: boolean | undefined;
writableAll?: boolean | undefined;
host?: string | undefined;
/**
* @default false
*/
ipv6Only?: boolean | undefined;
reusePort?: boolean | undefined;
path?: string | undefined;
port?: number | undefined;
readableAll?: boolean | undefined;
writableAll?: boolean | undefined;
}
interface ServerOpts {
/**
@@ -532,6 +533,21 @@ declare module "net" {
* @since v16.5.0
*/
keepAliveInitialDelay?: number | undefined;
/**
* Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`.
* @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode).
* @since v18.17.0, v20.1.0
*/
highWaterMark?: number | undefined;
/**
* `blockList` can be used for disabling inbound
* access to specific IP addresses, IP ranges, or IP subnets. This does not
* work if the server is behind a reverse proxy, NAT, etc. because the address
* checked against the block list is the address of the proxy, or the one
* specified by the NAT.
* @since v22.13.0
*/
blockList?: BlockList | undefined;
}
interface DropArgument {
localAddress?: string;
@@ -643,7 +659,7 @@ declare module "net" {
* Callback should take two arguments `err` and `count`.
* @since v0.9.7
*/
getConnections(cb: (error: Error | null, count: number) => void): void;
getConnections(cb: (error: Error | null, count: number) => void): this;
/**
* Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior).
* If the server is `ref`ed calling `ref()` again will have no effect.
@@ -783,6 +799,12 @@ declare module "net" {
* @since v15.0.0, v14.18.0
*/
rules: readonly string[];
/**
* Returns `true` if the `value` is a `net.BlockList`.
* @since v22.13.0
* @param value Any JS value
*/
static isBlockList(value: unknown): value is BlockList;
}
interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts {
timeout?: number | undefined;
@@ -812,7 +834,7 @@ declare module "net" {
* on port 8124:
*
* ```js
* const net = require('node:net');
* import net from 'node:net';
* const server = net.createServer((c) => {
* // 'connection' listener.
* console.log('client connected');
@@ -894,6 +916,9 @@ declare module "net" {
function getDefaultAutoSelectFamily(): boolean;
/**
* Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`.
* @param value The new default value.
* The initial default value is `true`, unless the command line option
* `--no-network-family-autoselection` is provided.
* @since v19.4.0
*/
function setDefaultAutoSelectFamily(value: boolean): void;
@@ -992,6 +1017,14 @@ declare module "net" {
* @since v15.14.0, v14.18.0
*/
readonly flowlabel: number;
/**
* @since v22.13.0
* @param input An input string containing an IP address and optional port,
* e.g. `123.1.2.3:1234` or `[1::1]:1234`.
* @returns Returns a `SocketAddress` if parsing was successful.
* Otherwise returns `undefined`.
*/
static parse(input: string): SocketAddress | undefined;
}
}
declare module "node:net" {

17
node_modules/@types/node/os.d.ts generated vendored
View File

@@ -3,9 +3,9 @@
* properties. It can be accessed using:
*
* ```js
* const os = require('node:os');
* import os from 'node:os';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/os.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js)
*/
declare module "os" {
interface CpuInfo {
@@ -241,7 +241,7 @@ declare module "os" {
* environment variables for the home directory before falling back to the
* operating system response.
*
* Throws a [`SystemError`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`.
* Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`.
* @since v6.0.0
*/
function userInfo(options: { encoding: "buffer" }): UserInfo<Buffer>;
@@ -417,13 +417,13 @@ declare module "os" {
const EOL: string;
/**
* Returns the operating system CPU architecture for which the Node.js binary was
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`,
* and `'x64'`.
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,
* `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`.
*
* The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v22.x/api/process.html#processarch).
* The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v24.x/api/process.html#processarch).
* @since v0.5.0
*/
function arch(): string;
function arch(): NodeJS.Architecture;
/**
* Returns a string identifying the kernel version.
*
@@ -445,7 +445,8 @@ declare module "os" {
*/
function platform(): NodeJS.Platform;
/**
* Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`.
* Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,
* `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`.
*
* On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.

View File

@@ -1,6 +1,6 @@
{
"name": "@types/node",
"version": "22.5.5",
"version": "24.0.7",
"description": "TypeScript definitions for node",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",
"license": "MIT",
@@ -170,11 +170,6 @@
"githubUsername": "victorperin",
"url": "https://github.com/victorperin"
},
{
"name": "Yongsheng Zhang",
"githubUsername": "ZYSzys",
"url": "https://github.com/ZYSzys"
},
{
"name": "NodeJS Contributors",
"githubUsername": "NodeJS",
@@ -199,10 +194,37 @@
"name": "Dmitry Semigradsky",
"githubUsername": "Semigradsky",
"url": "https://github.com/Semigradsky"
},
{
"name": "René",
"githubUsername": "Renegade334",
"url": "https://github.com/Renegade334"
},
{
"name": "Yagiz Nizipli",
"githubUsername": "anonrig",
"url": "https://github.com/anonrig"
}
],
"main": "",
"types": "index.d.ts",
"typesVersions": {
"<=5.1": {
"*": [
"ts5.1/*"
]
},
"<=5.6": {
"*": [
"ts5.6/*"
]
},
"<=5.7": {
"*": [
"ts5.7/*"
]
}
},
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
@@ -210,8 +232,9 @@
},
"scripts": {},
"dependencies": {
"undici-types": "~6.19.2"
"undici-types": "~7.8.0"
},
"typesPublisherContentHash": "49c6854801c6eca5f0c4debaa90673195b7385ea09dc082e76a86be2fa20430f",
"typeScriptVersion": "4.8"
"peerDependencies": {},
"typesPublisherContentHash": "9d4d0600f3777de66d31fc3650d20edf2918bca4267042e5be25f65fb4e92e06",
"typeScriptVersion": "5.1"
}

4
node_modules/@types/node/path.d.ts generated vendored
View File

@@ -11,9 +11,9 @@ declare module "path/win32" {
* paths. It can be accessed using:
*
* ```js
* const path = require('node:path');
* import path from 'node:path';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/path.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/path.js)
*/
declare module "path" {
namespace path {

View File

@@ -10,7 +10,7 @@
* * [Resource Timing](https://www.w3.org/TR/resource-timing-2/)
*
* ```js
* const { PerformanceObserver, performance } = require('node:perf_hooks');
* import { PerformanceObserver, performance } from 'node:perf_hooks';
*
* const obs = new PerformanceObserver((items) => {
* console.log(items.getEntries()[0].duration);
@@ -27,7 +27,7 @@
* performance.measure('A to B', 'A', 'B');
* });
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/perf_hooks.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/perf_hooks.js)
*/
declare module "perf_hooks" {
import { AsyncResource } from "node:async_hooks";
@@ -116,6 +116,20 @@ declare module "perf_hooks" {
class PerformanceMeasure extends PerformanceEntry {
readonly entryType: "measure";
}
interface UVMetrics {
/**
* Number of event loop iterations.
*/
readonly loopCount: number;
/**
* Number of events that have been processed by the event handler.
*/
readonly events: number;
/**
* Number of events that were waiting to be processed when the event provider was called.
*/
readonly eventsWaiting: number;
}
/**
* _This property is an extension by Node.js. It is not available in Web browsers._
*
@@ -166,6 +180,16 @@ declare module "perf_hooks" {
* @since v8.5.0
*/
readonly nodeStart: number;
/**
* This is a wrapper to the `uv_metrics_info` function.
* It returns the current set of event loop metrics.
*
* It is recommended to use this property inside a function whose execution was
* scheduled using `setImmediate` to avoid collecting metrics before finishing all
* operations scheduled during the current loop iteration.
* @since v22.8.0, v20.18.0
*/
readonly uvMetricsInfo: UVMetrics;
/**
* The high resolution millisecond timestamp at which the V8 platform was
* initialized.
@@ -355,10 +379,10 @@ declare module "perf_hooks" {
* A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed.
*
* ```js
* const {
* import {
* performance,
* PerformanceObserver,
* } = require('node:perf_hooks');
* } from 'node:perf_hooks';
*
* function someFunction() {
* console.log('hello world');
@@ -397,10 +421,10 @@ declare module "perf_hooks" {
* with respect to `performanceEntry.startTime`.
*
* ```js
* const {
* import {
* performance,
* PerformanceObserver,
* } = require('node:perf_hooks');
* } from 'node:perf_hooks';
*
* const obs = new PerformanceObserver((perfObserverList, observer) => {
* console.log(perfObserverList.getEntries());
@@ -440,10 +464,10 @@ declare module "perf_hooks" {
* equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`.
*
* ```js
* const {
* import {
* performance,
* PerformanceObserver,
* } = require('node:perf_hooks');
* } from 'node:perf_hooks';
*
* const obs = new PerformanceObserver((perfObserverList, observer) => {
* console.log(perfObserverList.getEntriesByName('meow'));
@@ -491,10 +515,10 @@ declare module "perf_hooks" {
* with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`.
*
* ```js
* const {
* import {
* performance,
* PerformanceObserver,
* } = require('node:perf_hooks');
* } from 'node:perf_hooks';
*
* const obs = new PerformanceObserver((perfObserverList, observer) => {
* console.log(perfObserverList.getEntriesByType('mark'));
@@ -544,10 +568,10 @@ declare module "perf_hooks" {
* Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`:
*
* ```js
* const {
* import {
* performance,
* PerformanceObserver,
* } = require('node:perf_hooks');
* } from 'node:perf_hooks';
*
* const obs = new PerformanceObserver((list, observer) => {
* // Called once asynchronously. `list` contains three items.
@@ -570,6 +594,11 @@ declare module "perf_hooks" {
buffered?: boolean | undefined;
},
): void;
/**
* @since v16.0.0
* @returns Current list of entries stored in the performance observer, emptying it out.
*/
takeRecords(): PerformanceEntry[];
}
/**
* Provides detailed network timing data regarding the loading of an application's resources.
@@ -816,7 +845,7 @@ declare module "perf_hooks" {
* detect.
*
* ```js
* const { monitorEventLoopDelay } = require('node:perf_hooks');
* import { monitorEventLoopDelay } from 'node:perf_hooks';
* const h = monitorEventLoopDelay({ resolution: 20 });
* h.enable();
* // Do something.
@@ -837,12 +866,12 @@ declare module "perf_hooks" {
* The minimum recordable value. Must be an integer value greater than 0.
* @default 1
*/
min?: number | bigint | undefined;
lowest?: number | bigint | undefined;
/**
* The maximum recordable value. Must be an integer value greater than min.
* @default Number.MAX_SAFE_INTEGER
*/
max?: number | bigint | undefined;
highest?: number | bigint | undefined;
/**
* The number of accuracy digits. Must be a number between 1 and 5.
* @default 3
@@ -865,8 +894,8 @@ declare module "perf_hooks" {
} from "perf_hooks";
global {
/**
* `PerformanceEntry` is a global reference for `require('node:perf_hooks').PerformanceEntry`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceentry
* `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceentry
* @since v19.0.0
*/
var PerformanceEntry: typeof globalThis extends {
@@ -875,8 +904,8 @@ declare module "perf_hooks" {
} ? T
: typeof _PerformanceEntry;
/**
* `PerformanceMark` is a global reference for `require('node:perf_hooks').PerformanceMark`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemark
* `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemark
* @since v19.0.0
*/
var PerformanceMark: typeof globalThis extends {
@@ -885,8 +914,8 @@ declare module "perf_hooks" {
} ? T
: typeof _PerformanceMark;
/**
* `PerformanceMeasure` is a global reference for `require('node:perf_hooks').PerformanceMeasure`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemeasure
* `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemeasure
* @since v19.0.0
*/
var PerformanceMeasure: typeof globalThis extends {
@@ -895,8 +924,8 @@ declare module "perf_hooks" {
} ? T
: typeof _PerformanceMeasure;
/**
* `PerformanceObserver` is a global reference for `require('node:perf_hooks').PerformanceObserver`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserver
* `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserver
* @since v19.0.0
*/
var PerformanceObserver: typeof globalThis extends {
@@ -905,8 +934,8 @@ declare module "perf_hooks" {
} ? T
: typeof _PerformanceObserver;
/**
* `PerformanceObserverEntryList` is a global reference for `require('node:perf_hooks').PerformanceObserverEntryList`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserverentrylist
* `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserverentrylist
* @since v19.0.0
*/
var PerformanceObserverEntryList: typeof globalThis extends {
@@ -915,8 +944,8 @@ declare module "perf_hooks" {
} ? T
: typeof _PerformanceObserverEntryList;
/**
* `PerformanceResourceTiming` is a global reference for `require('node:perf_hooks').PerformanceResourceTiming`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceresourcetiming
* `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceresourcetiming
* @since v19.0.0
*/
var PerformanceResourceTiming: typeof globalThis extends {
@@ -925,8 +954,8 @@ declare module "perf_hooks" {
} ? T
: typeof _PerformanceResourceTiming;
/**
* `performance` is a global reference for `require('node:perf_hooks').performance`
* @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performance
* `performance` is a global reference for `import { performance } from 'node:perf_hooks'`
* @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performance
* @since v16.0.0
*/
var performance: typeof globalThis extends {

203
node_modules/@types/node/process.d.ts generated vendored
View File

@@ -168,6 +168,84 @@ declare module "process" {
libUrl?: string | undefined;
lts?: string | undefined;
}
interface ProcessFeatures {
/**
* A boolean value that is `true` if the current Node.js build is caching builtin modules.
* @since v12.0.0
*/
readonly cached_builtins: boolean;
/**
* A boolean value that is `true` if the current Node.js build is a debug build.
* @since v0.5.5
*/
readonly debug: boolean;
/**
* A boolean value that is `true` if the current Node.js build includes the inspector.
* @since v11.10.0
*/
readonly inspector: boolean;
/**
* A boolean value that is `true` if the current Node.js build includes support for IPv6.
*
* Since all Node.js builds have IPv6 support, this value is always `true`.
* @since v0.5.3
* @deprecated This property is always true, and any checks based on it are redundant.
*/
readonly ipv6: boolean;
/**
* A boolean value that is `true` if the current Node.js build supports
* [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v24.x/api/modules.md#loading-ecmascript-modules-using-require).
* @since v22.10.0
*/
readonly require_module: boolean;
/**
* A boolean value that is `true` if the current Node.js build includes support for TLS.
* @since v0.5.3
*/
readonly tls: boolean;
/**
* A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS.
*
* In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support.
* This value is therefore identical to that of `process.features.tls`.
* @since v4.8.0
* @deprecated Use `process.features.tls` instead.
*/
readonly tls_alpn: boolean;
/**
* A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS.
*
* In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support.
* This value is therefore identical to that of `process.features.tls`.
* @since v0.11.13
* @deprecated Use `process.features.tls` instead.
*/
readonly tls_ocsp: boolean;
/**
* A boolean value that is `true` if the current Node.js build includes support for SNI in TLS.
*
* In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support.
* This value is therefore identical to that of `process.features.tls`.
* @since v0.5.3
* @deprecated Use `process.features.tls` instead.
*/
readonly tls_sni: boolean;
/**
* A value that is `"strip"` by default,
* `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if
* Node.js is run with `--no-experimental-strip-types`.
* @since v22.10.0
*/
readonly typescript: "strip" | "transform" | false;
/**
* A boolean value that is `true` if the current Node.js build includes support for libuv.
*
* Since it's not possible to build Node.js without libuv, this value is always `true`.
* @since v0.5.3
* @deprecated This property is always true, and any checks based on it are redundant.
*/
readonly uv: boolean;
}
interface ProcessVersions extends Dict<string> {
http_parser: string;
node: string;
@@ -197,10 +275,8 @@ declare module "process" {
| "loong64"
| "mips"
| "mipsel"
| "ppc"
| "ppc64"
| "riscv64"
| "s390"
| "s390x"
| "x64";
type Signals =
@@ -273,11 +349,43 @@ declare module "process" {
TZ?: string;
}
interface HRTime {
/**
* This is the legacy version of {@link process.hrtime.bigint()}
* before bigint was introduced in JavaScript.
*
* The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`,
* where `nanoseconds` is the remaining part of the real time that can't be represented in second precision.
*
* `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time.
* If the parameter passed in is not a tuple `Array`, a TypeError will be thrown.
* Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior.
*
* These times are relative to an arbitrary time in the past,
* and not related to the time of day and therefore not subject to clock drift.
* The primary use is for measuring performance between intervals:
* ```js
* const { hrtime } = require('node:process');
* const NS_PER_SEC = 1e9;
* const time = hrtime();
* // [ 1800216, 25 ]
*
* setTimeout(() => {
* const diff = hrtime(time);
* // [ 1, 552 ]
*
* console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
* // Benchmark took 1000000552 nanoseconds
* }, 1000);
* ```
* @since 0.7.6
* @legacy Use {@link process.hrtime.bigint()} instead.
* @param time The result of a previous call to `process.hrtime()`
*/
(time?: [number, number]): [number, number];
/**
* The `bigint` version of the `{@link hrtime()}` method returning the current high-resolution real time in nanoseconds as a `bigint`.
* The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`.
*
* Unlike `{@link hrtime()}`, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s.
* Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s.
* ```js
* import { hrtime } from 'node:process';
*
@@ -292,6 +400,7 @@ declare module "process" {
* // Benchmark took 1154389282 nanoseconds
* }, 1000);
* ```
* @since v10.7.0
*/
bigint(): bigint;
}
@@ -638,7 +747,7 @@ declare module "process" {
* should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()`
* unless there are specific reasons such as custom dlopen flags or loading from ES modules.
*
* The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v22.x/api/os.html#dlopen-constants)`
* The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v24.x/api/os.html#dlopen-constants)`
* documentation for details.
*
* An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon
@@ -1380,6 +1489,18 @@ declare module "process" {
* @since v9.2.0, v8.10.0, v6.13.0
*/
readonly ppid: number;
/**
* The `process.threadCpuUsage()` method returns the user and system CPU time usage of
* the current worker thread, in an object with properties `user` and `system`, whose
* values are microsecond values (millionth of a second).
*
* The result of a previous call to `process.threadCpuUsage()` can be passed as the
* argument to the function, to get a diff reading.
* @since v23.9.0
* @param previousValue A previous return value from calling
* `process.threadCpuUsage()`
*/
threadCpuUsage(previousValue?: CpuUsage): CpuUsage;
/**
* The `process.title` property returns the current process title (i.e. returns
* the current value of `ps`). Assigning a new value to `process.title` modifies
@@ -1400,7 +1521,8 @@ declare module "process" {
title: string;
/**
* The operating system CPU architecture for which the Node.js binary was compiled.
* Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`.
* Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`,
* `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`.
*
* ```js
* import { arch } from 'node:process';
@@ -1456,13 +1578,11 @@ declare module "process" {
* See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more
* information.
* @since v19.6.0, v18.15.0
* @experimental
*/
constrainedMemory(): number;
/**
* Gets the amount of free memory that is still available to the process (in bytes).
* See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v22.x/api/process.html#processavailablememory) for more information.
* @experimental
* See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v24.x/api/process.html#processavailablememory) for more information.
* @since v20.13.0
*/
availableMemory(): number;
@@ -1583,7 +1703,7 @@ declare module "process" {
*/
nextTick(callback: Function, ...args: any[]): void;
/**
* This API is available through the [--experimental-permission](https://nodejs.org/api/cli.html#--experimental-permission) flag.
* This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag.
*
* `process.permission` is an object whose methods are used to manage permissions for the current process.
* Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model).
@@ -1612,16 +1732,7 @@ declare module "process" {
* @since v3.0.0
*/
readonly release: ProcessRelease;
features: {
inspector: boolean;
debug: boolean;
uv: boolean;
ipv6: boolean;
tls_alpn: boolean;
tls_sni: boolean;
tls_ocsp: boolean;
tls: boolean;
};
readonly features: ProcessFeatures;
/**
* `process.umask()` returns the Node.js process's file mode creation mask. Child
* processes inherit the mask from the parent process.
@@ -1744,7 +1855,7 @@ declare module "process" {
allowedNodeEnvironmentFlags: ReadonlySet<string>;
/**
* `process.report` is an object whose methods are used to generate diagnostic reports for the current process.
* Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v22.x/api/report.html).
* Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v24.x/api/report.html).
* @since v11.8.0
*/
report: ProcessReport;
@@ -1809,6 +1920,56 @@ declare module "process" {
* @since v0.8.0
*/
traceDeprecation: boolean;
/**
* An object is "refable" if it implements the Node.js "Refable protocol".
* Specifically, this means that the object implements the `Symbol.for('nodejs.ref')`
* and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js
* event loop alive, while "unref'd" objects will not. Historically, this was
* implemented by using `ref()` and `unref()` methods directly on the objects.
* This pattern, however, is being deprecated in favor of the "Refable protocol"
* in order to better support Web Platform API types whose APIs cannot be modified
* to add `ref()` and `unref()` methods but still need to support that behavior.
* @since v22.14.0
* @experimental
* @param maybeRefable An object that may be "refable".
*/
ref(maybeRefable: any): void;
/**
* An object is "unrefable" if it implements the Node.js "Refable protocol".
* Specifically, this means that the object implements the `Symbol.for('nodejs.ref')`
* and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js
* event loop alive, while "unref'd" objects will not. Historically, this was
* implemented by using `ref()` and `unref()` methods directly on the objects.
* This pattern, however, is being deprecated in favor of the "Refable protocol"
* in order to better support Web Platform API types whose APIs cannot be modified
* to add `ref()` and `unref()` methods but still need to support that behavior.
* @since v22.14.0
* @experimental
* @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;

View File

@@ -8,7 +8,7 @@
* can be accessed using:
*
* ```js
* const punycode = require('punycode');
* import punycode from 'node:punycode';
* ```
*
* [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is
@@ -24,7 +24,7 @@
* made available to developers as a convenience. Fixes or other modifications to
* the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project.
* @deprecated Since v7.0.0 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/punycode.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/punycode.js)
*/
declare module "punycode" {
/**

View File

@@ -3,13 +3,13 @@
* query strings. It can be accessed using:
*
* ```js
* const querystring = require('node:querystring');
* import querystring from 'node:querystring';
* ```
*
* `querystring` is more performant than `URLSearchParams` but is not a
* standardized API. Use `URLSearchParams` when performance is not critical or
* when compatibility with browser code is desirable.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/querystring.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/querystring.js)
*/
declare module "querystring" {
interface StringifyOptions {
@@ -37,9 +37,8 @@ declare module "querystring" {
| string
| number
| boolean
| readonly string[]
| readonly number[]
| readonly boolean[]
| bigint
| ReadonlyArray<string | number | boolean | bigint>
| null
>
{}

View File

@@ -1,6 +1,6 @@
/**
* The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream
* (such as [`process.stdin`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdin)) one line at a time.
* The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream
* (such as [`process.stdin`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdin)) one line at a time.
*
* To use the promise-based APIs:
*
@@ -31,7 +31,7 @@
*
* Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be
* received on the `input` stream.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/readline.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/readline.js)
*/
declare module "readline" {
import { Abortable, EventEmitter } from "node:events";
@@ -46,12 +46,12 @@ declare module "readline" {
}
/**
* Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a
* single `input` [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream.
* single `input` [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream.
* The `output` stream is used to print prompts for user input that arrives on,
* 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.
@@ -100,7 +100,7 @@ declare module "readline" {
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor
* @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor
*/
protected constructor(
input: NodeJS.ReadableStream,
@@ -114,7 +114,7 @@ declare module "readline" {
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor
* @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor
*/
protected constructor(options: ReadLineOptions);
/**
@@ -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
@@ -304,7 +309,7 @@ declare module "readline" {
prependOnceListener(event: "SIGINT", listener: () => void): this;
prependOnceListener(event: "SIGTSTP", listener: () => void): this;
prependOnceListener(event: "history", listener: (history: string[]) => void): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string>;
[Symbol.asyncIterator](): NodeJS.AsyncIterator<string>;
}
export type ReadLine = Interface; // type forwarded for backwards compatibility
export type Completer = (line: string) => CompleterResult;
@@ -314,35 +319,84 @@ declare module "readline" {
) => void;
export type CompleterResult = [string[], string];
export interface ReadLineOptions {
/**
* The [`Readable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream to listen to
*/
input: NodeJS.ReadableStream;
/**
* The [`Writable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream to write readline data to.
*/
output?: NodeJS.WritableStream | undefined;
/**
* An optional function used for Tab autocompletion.
*/
completer?: Completer | AsyncCompleter | undefined;
/**
* `true` if the `input` and `output` streams should be treated like a TTY,
* and have ANSI/VT100 escape codes written to it.
* Default: checking `isTTY` on the `output` stream upon instantiation.
*/
terminal?: boolean | undefined;
/**
* Initial list of history lines. This option makes sense
* only if `terminal` is set to `true` by the user or by an internal `output`
* check, otherwise the history caching mechanism is not initialized at all.
* Initial list of history lines.
* This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check,
* otherwise the history caching mechanism is not initialized at all.
* @default []
*/
history?: string[] | undefined;
historySize?: number | undefined;
prompt?: string | undefined;
crlfDelay?: number | undefined;
/**
* If `true`, when a new input line added
* to the history list duplicates an older one, this removes the older line
* from the list.
* Maximum number of history lines retained.
* To disable the history set this value to `0`.
* This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check,
* otherwise the history caching mechanism is not initialized at all.
* @default 30
*/
historySize?: number | undefined;
/**
* If `true`, when a new input line added to the history list duplicates an older one,
* this removes the older line from the list.
* @default false
*/
removeHistoryDuplicates?: boolean | undefined;
/**
* The prompt string to use.
* @default "> "
*/
prompt?: string | undefined;
/**
* If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds,
* both `\r` and `\n` will be treated as separate end-of-line input.
* `crlfDelay` will be coerced to a number no less than `100`.
* It can be set to `Infinity`, in which case
* `\r` followed by `\n` will always be considered a single newline
* (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v24.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter).
* @default 100
*/
crlfDelay?: number | undefined;
/**
* The duration `readline` will wait for a character
* (when reading an ambiguous key sequence in milliseconds
* one that can both form a complete key sequence using the input read so far
* and can take additional input to complete a longer key sequence).
* @default 500
*/
escapeCodeTimeout?: number | undefined;
/**
* The number of spaces a tab is equal to (minimum 1).
* @default 8
*/
tabSize?: number | undefined;
/**
* Allows closing the interface using an AbortSignal.
* Aborting the signal will internally call `close` on the interface.
*/
signal?: AbortSignal | undefined;
}
/**
* The `readline.createInterface()` method creates a new `readline.Interface` instance.
*
* ```js
* const readline = require('node:readline');
* import readline from 'node:readline';
* const rl = readline.createInterface({
* input: process.stdin,
* output: process.stdout,
@@ -398,7 +452,7 @@ declare module "readline" {
* implement a small command-line interface:
*
* ```js
* const readline = require('node:readline');
* import readline from 'node:readline';
* const rl = readline.createInterface({
* input: process.stdin,
* output: process.stdout,
@@ -430,8 +484,8 @@ declare module "readline" {
* well as a `for await...of` loop:
*
* ```js
* const fs = require('node:fs');
* const readline = require('node:readline');
* import fs from 'node:fs';
* import readline from 'node:readline';
*
* async function processLineByLine() {
* const fileStream = fs.createReadStream('input.txt');
@@ -455,8 +509,8 @@ declare module "readline" {
* Alternatively, one could use the `'line'` event:
*
* ```js
* const fs = require('node:fs');
* const readline = require('node:readline');
* import fs from 'node:fs';
* import readline from 'node:readline';
*
* const rl = readline.createInterface({
* input: fs.createReadStream('sample.txt'),
@@ -471,9 +525,9 @@ declare module "readline" {
* Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied:
*
* ```js
* const { once } = require('node:events');
* const { createReadStream } = require('node:fs');
* const { createInterface } = require('node:readline');
* import { once } from 'node:events';
* import { createReadStream } from 'node:fs';
* import { createInterface } from 'node:readline';
*
* (async function processLineByLine() {
* try {
@@ -503,7 +557,7 @@ declare module "readline" {
cols: number;
}
/**
* The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream
* The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream
* in a specified direction identified by `dir`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
@@ -511,7 +565,7 @@ declare module "readline" {
*/
export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean;
/**
* The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream from
* The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream from
* the current position of the cursor down.
* @since v0.7.7
* @param callback Invoked once the operation completes.
@@ -520,7 +574,7 @@ declare module "readline" {
export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean;
/**
* The `readline.cursorTo()` method moves cursor to the specified position in a
* given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`.
* given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
@@ -528,7 +582,7 @@ declare module "readline" {
export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean;
/**
* The `readline.moveCursor()` method moves the cursor _relative_ to its current
* position in a given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`.
* position in a given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.

View File

@@ -1,10 +1,14 @@
/**
* @since v17.0.0
* @experimental
*/
declare module "readline/promises" {
import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline";
import { Abortable } from "node:events";
import {
CompleterResult,
Direction,
Interface as _Interface,
ReadLineOptions as _ReadLineOptions,
} from "node:readline";
/**
* Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a
* single `input` `Readable` stream and a single `output` `Writable` stream.
@@ -111,11 +115,18 @@ declare module "readline/promises" {
*/
rollback(): this;
}
type Completer = (line: string) => CompleterResult | Promise<CompleterResult>;
interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> {
/**
* An optional function used for Tab autocompletion.
*/
completer?: Completer | undefined;
}
/**
* The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance.
*
* ```js
* const readlinePromises = require('node:readline/promises');
* import readlinePromises from 'node:readline/promises';
* const rl = readlinePromises.createInterface({
* input: process.stdin,
* output: process.stdout,
@@ -140,7 +151,7 @@ declare module "readline/promises" {
function createInterface(
input: NodeJS.ReadableStream,
output?: NodeJS.WritableStream,
completer?: Completer | AsyncCompleter,
completer?: Completer,
terminal?: boolean,
): Interface;
function createInterface(options: ReadLineOptions): Interface;

38
node_modules/@types/node/repl.d.ts generated vendored
View File

@@ -4,9 +4,9 @@
* applications. It can be accessed using:
*
* ```js
* const repl = require('node:repl');
* import repl from 'node:repl';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/repl.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/repl.js)
*/
declare module "repl" {
import { AsyncCompleter, Completer, Interface } from "node:readline";
@@ -37,12 +37,10 @@ declare module "repl" {
terminal?: boolean | undefined;
/**
* The function to be used when evaluating each given line of input.
* Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can
* **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can
* error with `repl.Recoverable` to indicate the input was incomplete and prompt for
* additional lines.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_default_evaluation
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_custom_evaluation_functions
* additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#custom-evaluation-functions)
* section for more details.
*/
eval?: REPLEval | undefined;
/**
@@ -74,13 +72,13 @@ declare module "repl" {
* The function to invoke to format the output of each command before writing to `output`.
* @default a wrapper for `util.inspect`
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_customizing_repl_output
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_customizing_repl_output
*/
writer?: REPLWriter | undefined;
/**
* An optional function used for custom Tab auto completion.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#readline_use_of_the_completer_function
* @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#readline_use_of_the_completer_function
*/
completer?: Completer | AsyncCompleter | undefined;
/**
@@ -130,7 +128,7 @@ declare module "repl" {
* or directly using the JavaScript `new` keyword.
*
* ```js
* const repl = require('node:repl');
* import repl from 'node:repl';
*
* const options = { useColors: true };
*
@@ -168,33 +166,33 @@ declare module "repl" {
/**
* A value indicating whether the REPL is currently in "editor mode".
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_commands_and_special_keys
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_commands_and_special_keys
*/
readonly editorMode: boolean;
/**
* A value indicating whether the `_` variable has been assigned.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly underscoreAssigned: boolean;
/**
* The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL).
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly last: any;
/**
* A value indicating whether the `_error` variable has been assigned.
*
* @since v9.8.0
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly underscoreErrAssigned: boolean;
/**
* The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL).
*
* @since v9.8.0
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly lastError: any;
/**
@@ -246,7 +244,7 @@ declare module "repl" {
*
* `REPLServer` cannot be subclassed due to implementation specifics in NodeJS.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_class_replserver
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_class_replserver
*/
private constructor();
/**
@@ -257,7 +255,7 @@ declare module "repl" {
* The following example shows two new commands added to the REPL instance:
*
* ```js
* const repl = require('node:repl');
* import repl from 'node:repl';
*
* const replServer = repl.start({ prompt: '> ' });
* replServer.defineCommand('sayhello', {
@@ -291,7 +289,7 @@ declare module "repl" {
* The `replServer.displayPrompt()` method readies the REPL instance for input
* from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input.
*
* When multi-line input is being entered, an ellipsis is printed rather than the
* When multi-line input is being entered, a pipe `'|'` is printed rather than the
* 'prompt'.
*
* When `preserveCursor` is `true`, the cursor placement will not be reset to `0`.
@@ -407,7 +405,7 @@ declare module "repl" {
* If `options` is a string, then it specifies the input prompt:
*
* ```js
* const repl = require('node:repl');
* import repl from 'node:repl';
*
* // a Unix style prompt
* repl.start('$ ');
@@ -418,7 +416,7 @@ declare module "repl" {
/**
* Indicates a recoverable error that a `REPLServer` can use to support multi-line input.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_recoverable_errors
* @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_recoverable_errors
*/
class Recoverable extends SyntaxError {
err: Error;

4
node_modules/@types/node/sea.d.ts generated vendored
View File

@@ -111,7 +111,7 @@
* ```
* @since v19.7.0, v18.16.0
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v22.x/src/node_sea.cc)
* @see [source](https://github.com/nodejs/node/blob/v24.x/src/node_sea.cc)
*/
declare module "node:sea" {
type AssetKey = string;
@@ -149,5 +149,5 @@ declare module "node:sea" {
* writes to the returned array buffer is likely to result in a crash.
* @since v20.12.0
*/
function getRawAsset(key: AssetKey): string | ArrayBuffer;
function getRawAsset(key: AssetKey): ArrayBuffer;
}

529
node_modules/@types/node/sqlite.d.ts generated vendored
View File

@@ -40,37 +40,243 @@
* ```
* @since v22.5.0
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/sqlite.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js)
*/
declare module "node:sqlite" {
type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView;
type SQLOutputValue = null | number | bigint | string | Uint8Array;
/** @deprecated Use `SQLInputValue` or `SQLOutputValue` instead. */
type SupportedValueType = SQLOutputValue;
interface DatabaseSyncOptions {
/**
* If `true`, the database is opened by the constructor.
* When this value is `false`, the database must be opened via the `open()` method.
* If `true`, the database is opened by the constructor. When
* this value is `false`, the database must be opened via the `open()` method.
* @since v22.5.0
* @default true
*/
open?: boolean | undefined;
/**
* If `true`, foreign key constraints
* are enabled. This is recommended but can be disabled for compatibility with
* legacy database schemas. The enforcement of foreign key constraints can be
* enabled and disabled after opening the database using
* [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
* @since v22.10.0
* @default true
*/
enableForeignKeyConstraints?: boolean | undefined;
/**
* If `true`, SQLite will accept
* [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote).
* This is not recommended but can be
* enabled for compatibility with legacy database schemas.
* @since v22.10.0
* @default false
*/
enableDoubleQuotedStringLiterals?: boolean | undefined;
/**
* If `true`, the database is opened in read-only mode.
* If the database does not exist, opening it will fail.
* @since v22.12.0
* @default false
*/
readOnly?: boolean | undefined;
/**
* If `true`, the `loadExtension` SQL function
* and the `loadExtension()` method are enabled.
* You can call `enableLoadExtension(false)` later to disable this feature.
* @since v22.13.0
* @default false
*/
allowExtension?: boolean | undefined;
/**
* The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of
* time that SQLite will wait for a database lock to be released before
* returning an error.
* @since v24.0.0
* @default 0
*/
timeout?: number | undefined;
}
interface CreateSessionOptions {
/**
* A specific table to track changes for. By default, changes to all tables are tracked.
* @since v22.12.0
*/
table?: string | undefined;
/**
* Name of the database to track. This is useful when multiple databases have been added using
* [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html).
* @since v22.12.0
* @default 'main'
*/
db?: string | undefined;
}
interface ApplyChangesetOptions {
/**
* Skip changes that, when targeted table name is supplied to this function, return a truthy value.
* By default, all changes are attempted.
* @since v22.12.0
*/
filter?: ((tableName: string) => boolean) | undefined;
/**
* A function that determines how to handle conflicts. The function receives one argument,
* which can be one of the following values:
*
* * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values.
* * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist.
* * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key.
* * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation.
* * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint
* violation.
*
* The function should return one of the following values:
*
* * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes.
* * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with
`SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts).
* * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database.
*
* When an error is thrown in the conflict handler or when any other value is returned from the handler,
* applying the changeset is aborted and the database is rolled back.
*
* **Default**: A function that returns `SQLITE_CHANGESET_ABORT`.
* @since v22.12.0
*/
onConflict?: ((conflictType: number) => number) | undefined;
}
interface FunctionOptions {
/**
* If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is
* set on the created function.
* @default false
*/
deterministic?: boolean | undefined;
/**
* If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on
* the created function.
* @default false
*/
directOnly?: boolean | undefined;
/**
* If `true`, integer arguments to `function`
* are converted to `BigInt`s. If `false`, integer arguments are passed as
* JavaScript numbers.
* @default false
*/
useBigIntArguments?: boolean | undefined;
/**
* 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;
}
interface AggregateOptions<T extends SQLInputValue = SQLInputValue> extends FunctionOptions {
/**
* The identity value for the aggregation function. This value is used when the aggregation
* function is initialized. When a `Function` is passed the identity will be its return value.
*/
start: T | (() => T);
/**
* The function to call for each row in the aggregation. The
* function receives the current state and the row value. The return value of
* this function should be the new state.
*/
step: (accumulator: T, ...args: SQLOutputValue[]) => T;
/**
* The function to call to get the result of the
* aggregation. The function receives the final state and should return the
* result of the aggregation.
*/
result?: ((accumulator: T) => SQLInputValue) | undefined;
/**
* When this function is provided, the `aggregate` method will work as a window function.
* The function receives the current state and the dropped row value. The return value of this function should be the
* new state.
*/
inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | 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.
* @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);
/**
* Registers a new aggregate function with the SQLite database. This method is a wrapper around
* [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html).
*
* When used as a window function, the `result` function will be called multiple times.
*
* ```js
* import { DatabaseSync } from 'node:sqlite';
*
* const db = new DatabaseSync(':memory:');
* db.exec(`
* CREATE TABLE t3(x, y);
* INSERT INTO t3 VALUES ('a', 4),
* ('b', 5),
* ('c', 3),
* ('d', 8),
* ('e', 1);
* `);
*
* db.aggregate('sumint', {
* start: 0,
* step: (acc, value) => acc + value,
* });
*
* db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }
* ```
* @since v24.0.0
* @param name The name of the SQLite function to create.
* @param options Function configuration settings.
*/
aggregate(name: string, options: AggregateOptions): void;
aggregate<T extends SQLInputValue>(name: string, options: AggregateOptions<T>): void;
/**
* 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).
* @since v22.5.0
*/
close(): void;
/**
* 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.
* @since v22.13.0
* @param path The path to the shared library to load.
*/
loadExtension(path: string): void;
/**
* Enables or disables the `loadExtension` SQL function, and the `loadExtension()`
* method. When `allowExtension` is `false` when constructing, you cannot enable
* loading extensions for security reasons.
* @since v22.13.0
* @param allow Whether to allow loading extensions.
*/
enableLoadExtension(allow: boolean): void;
/**
* This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html)
* @since v24.0.0
* @param dbName Name of the database. 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 The location of the database file. When using an in-memory database,
* this method returns null.
*/
location(dbName?: string): string | null;
/**
* This method allows one or more SQL statements to be executed without returning
* any results. This method is useful when executing SQL statements read from a
@@ -80,7 +286,36 @@ declare module "node:sqlite" {
*/
exec(sql: string): 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
* This method is used to create SQLite user-defined functions. This method is a
* wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html).
* @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`.
*/
function(
name: string,
options: FunctionOptions,
func: (...args: SQLOutputValue[]) => SQLInputValue,
): void;
function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void;
/**
* Whether the database is currently open or not.
* @since v22.15.0
*/
readonly isOpen: boolean;
/**
* Whether the database is currently within a transaction. This method
* is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html).
* @since v24.0.0
*/
readonly isTransaction: 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
*/
@@ -93,8 +328,112 @@ declare module "node:sqlite" {
* @return The prepared statement.
*/
prepare(sql: string): StatementSync;
/**
* Creates and attaches a session to the database. This method is a wrapper around
* [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and
* [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html).
* @param options The configuration options for the session.
* @returns A session handle.
* @since v22.12.0
*/
createSession(options?: CreateSessionOptions): Session;
/**
* An exception is thrown if the database is not
* open. This method is a wrapper around
* [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html).
*
* ```js
* const sourceDb = new DatabaseSync(':memory:');
* const targetDb = new DatabaseSync(':memory:');
*
* sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
* targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
*
* const session = sourceDb.createSession();
*
* const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
* insert.run(1, 'hello');
* insert.run(2, 'world');
*
* const changeset = session.changeset();
* targetDb.applyChangeset(changeset);
* // Now that the changeset has been applied, targetDb contains the same data as sourceDb.
* ```
* @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 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
*/
interface Session {
/**
* Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times.
* An exception is thrown if the database or the session is not open. This method is a wrapper around
* [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html).
* @returns Binary changeset that can be applied to other databases.
* @since v22.12.0
*/
changeset(): Uint8Array;
/**
* Similar to the method above, but generates a more compact patchset. See
* [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets)
* in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a
* wrapper around
* [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html).
* @returns Binary patchset that can be applied to other databases.
* @since v22.12.0
*/
patchset(): Uint8Array;
/**
* Closes the session. An exception is thrown if the database or the session is not open. This method is a
* wrapper around
* [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html).
*/
close(): void;
}
interface StatementColumnMetadata {
/**
* The unaliased name of the column in the origin
* table, or `null` if the column is the result of an expression or subquery.
* This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html).
*/
column: string | null;
/**
* The unaliased name of the origin database, or
* `null` if the column is the result of an expression or subquery. This
* property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html).
*/
database: string | null;
/**
* The name assigned to the column in the result set of a
* `SELECT` statement. This property is the result of
* [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html).
*/
name: string;
/**
* The unaliased name of the origin table, or `null` if
* the column is the result of an expression or subquery. This property is the
* result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html).
*/
table: string | null;
/**
* The declared data type of the column, or `null` if the
* column is the result of an expression or subquery. This property is the
* result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html).
*/
type: string | null;
}
type SupportedValueType = null | number | bigint | string | Uint8Array;
interface StatementResultingChanges {
/**
* The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement.
@@ -134,18 +473,27 @@ declare module "node:sqlite" {
* @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of
* the row.
*/
all(...anonymousParameters: SupportedValueType[]): unknown[];
all(...anonymousParameters: SQLInputValue[]): Record<string, SQLOutputValue>[];
all(
namedParameters: Record<string, SupportedValueType>,
...anonymousParameters: SupportedValueType[]
): unknown[];
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[]
): Record<string, SQLOutputValue>[];
/**
* This method returns the source SQL of the prepared statement with parameter
* placeholders replaced by values. This method is a wrapper around [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html).
* @since v22.5.0
* @return The source SQL expanded to include parameter values.
* This method is used to retrieve information about the columns returned by the
* prepared statement.
* @since v23.11.0
* @returns An array of objects. Each object corresponds to a column
* in the prepared statement, and contains the following properties:
*/
expandedSQL(): string;
columns(): StatementColumnMetadata[];
/**
* The source SQL text of the prepared statement with parameter
* placeholders replaced by the values that were used during the most recent
* execution of this prepared statement. This property is a wrapper around
* [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html).
* @since v22.5.0
*/
readonly expandedSQL: string;
/**
* This method executes a prepared statement and returns the first result as an
* object. If the prepared statement does not return any results, this method
@@ -157,8 +505,29 @@ declare module "node:sqlite" {
* @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no
* rows were returned from the database then this method returns `undefined`.
*/
get(...anonymousParameters: SupportedValueType[]): unknown;
get(namedParameters: Record<string, SupportedValueType>, ...anonymousParameters: SupportedValueType[]): unknown;
get(...anonymousParameters: SQLInputValue[]): Record<string, SQLOutputValue> | undefined;
get(
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[]
): Record<string, SQLOutputValue> | undefined;
/**
* This method executes a prepared statement and returns an iterator of
* objects. If the prepared statement does not return any results, this method
* returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using
* the values in `namedParameters` and `anonymousParameters`.
* @since v22.13.0
* @param namedParameters An optional object used to bind named parameters.
* The keys of this object are used to configure the mapping.
* @param anonymousParameters Zero or more values to bind to anonymous parameters.
* @returns An iterable iterator of objects. Each object corresponds to a row
* returned by executing the prepared statement. The keys and values of each
* object correspond to the column names and values of the row.
*/
iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator<Record<string, SQLOutputValue>>;
iterate(
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[]
): NodeJS.Iterator<Record<string, SQLOutputValue>>;
/**
* This method executes a prepared statement and returns an object summarizing the
* resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the
@@ -167,10 +536,10 @@ declare module "node:sqlite" {
* @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping.
* @param anonymousParameters Zero or more values to bind to anonymous parameters.
*/
run(...anonymousParameters: SupportedValueType[]): StatementResultingChanges;
run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges;
run(
namedParameters: Record<string, SupportedValueType>,
...anonymousParameters: SupportedValueType[]
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[]
): StatementResultingChanges;
/**
* The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding
@@ -191,6 +560,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
@@ -203,11 +579,110 @@ declare module "node:sqlite" {
*/
setReadBigInts(enabled: boolean): void;
/**
* This method returns the source SQL of the prepared statement. This method is a
* The source SQL text of the prepared statement. This property is a
* wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html).
* @since v22.5.0
* @return The source SQL used to create this prepared statement.
*/
sourceSQL(): string;
readonly sourceSQL: string;
}
interface BackupOptions {
/**
* Name of the source database. This can be `'main'` (the default primary database) or any other
* database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html)
* @default 'main'
*/
source?: string | undefined;
/**
* Name of the target database. This can be `'main'` (the default primary database) or any other
* database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html)
* @default 'main'
*/
target?: string | undefined;
/**
* Number of pages to be transmitted in each batch of the backup.
* @default 100
*/
rate?: number | undefined;
/**
* Callback function that will be called with the number of pages copied and the total number of
* pages.
*/
progress?: ((progressInfo: BackupProgressInfo) => void) | undefined;
}
interface BackupProgressInfo {
totalPages: number;
remainingPages: number;
}
/**
* This method makes a database backup. This method abstracts the
* [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit),
* [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep)
* and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions.
*
* The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same
* `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause
* the backup process to restart.
*
* ```js
* import { backup, DatabaseSync } from 'node:sqlite';
*
* const sourceDb = new DatabaseSync('source.db');
* const totalPagesTransferred = await backup(sourceDb, 'backup.db', {
* rate: 1, // Copy one page at a time.
* progress: ({ totalPages, remainingPages }) => {
* console.log('Backup in progress', { totalPages, remainingPages });
* },
* });
*
* console.log('Backup completed', totalPagesTransferred);
* ```
* @since v23.8.0
* @param sourceDb The database to backup. The source database must be open.
* @param path The path where the backup will be created. If the file already exists,
* the contents will be overwritten.
* @param options Optional configuration for the backup. The
* following properties are supported:
* @returns A promise that resolves when the backup is completed and rejects if an error occurs.
*/
function backup(sourceDb: DatabaseSync, path: string | Buffer | URL, options?: BackupOptions): Promise<void>;
/**
* @since v22.13.0
*/
namespace constants {
/**
* The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values.
* @since v22.14.0
*/
const SQLITE_CHANGESET_DATA: number;
/**
* The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database.
* @since v22.14.0
*/
const SQLITE_CHANGESET_NOTFOUND: number;
/**
* This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.
* @since v22.14.0
*/
const SQLITE_CHANGESET_CONFLICT: number;
/**
* If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back.
* @since v22.14.0
*/
const SQLITE_CHANGESET_FOREIGN_KEY: number;
/**
* Conflicting changes are omitted.
* @since v22.12.0
*/
const SQLITE_CHANGESET_OMIT: number;
/**
* Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`.
* @since v22.12.0
*/
const SQLITE_CHANGESET_REPLACE: number;
/**
* Abort when a change encounters a conflict and roll back database.
* @since v22.12.0
*/
const SQLITE_CHANGESET_ABORT: number;
}
}

1980
node_modules/@types/node/stream.d.ts generated vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,37 @@
/**
* The utility consumer functions provide common options for consuming
* streams.
* @since v16.7.0
*/
declare module "stream/consumers" {
import { Blob as NodeBlob } from "node:buffer";
import { Readable } from "node:stream";
function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable<any>): Promise<Buffer>;
function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable<any>): Promise<string>;
function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable<any>): Promise<ArrayBuffer>;
function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable<any>): Promise<NodeBlob>;
function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable<any>): Promise<unknown>;
import { ReadableStream as WebReadableStream } from "node:stream/web";
/**
* @since v16.7.0
* @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream.
*/
function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<ArrayBuffer>;
/**
* @since v16.7.0
* @returns Fulfills with a `Blob` containing the full contents of the stream.
*/
function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<NodeBlob>;
/**
* @since v16.7.0
* @returns Fulfills with a `Buffer` containing the full contents of the stream.
*/
function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<Buffer>;
/**
* @since v16.7.0
* @returns Fulfills with the contents of the stream parsed as a
* UTF-8 encoded string that is then passed through `JSON.parse()`.
*/
function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<unknown>;
/**
* @since v16.7.0
* @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string.
*/
function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<string>;
}
declare module "node:stream/consumers" {
export * from "stream/consumers";

View File

@@ -1,12 +1,19 @@
declare module "stream/promises" {
import {
FinishedOptions,
FinishedOptions as _FinishedOptions,
PipelineDestination,
PipelineOptions,
PipelinePromise,
PipelineSource,
PipelineTransform,
} from "node:stream";
interface FinishedOptions extends _FinishedOptions {
/**
* If true, removes the listeners registered by this function before the promise is fulfilled.
* @default false
*/
cleanup?: boolean | undefined;
}
function finished(
stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream,
options?: FinishedOptions,

View File

@@ -97,7 +97,7 @@ declare module "stream/web" {
signal?: AbortSignal;
}
interface ReadableStreamGenericReader {
readonly closed: Promise<undefined>;
readonly closed: Promise<void>;
cancel(reason?: any): Promise<void>;
}
type ReadableStreamController<T> = ReadableStreamDefaultController<T>;
@@ -166,6 +166,9 @@ declare module "stream/web" {
interface ReadableStreamErrorCallback {
(reason: any): void | PromiseLike<void>;
}
interface ReadableStreamAsyncIterator<T> extends NodeJS.AsyncIterator<T, NodeJS.BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): ReadableStreamAsyncIterator<T>;
}
/** This Streams API interface represents a readable stream of byte data. */
interface ReadableStream<R = any> {
readonly locked: boolean;
@@ -176,8 +179,8 @@ declare module "stream/web" {
pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
tee(): [ReadableStream<R>, ReadableStream<R>];
values(options?: { preventCancel?: boolean }): AsyncIterableIterator<R>;
[Symbol.asyncIterator](): AsyncIterableIterator<R>;
values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator<R>;
[Symbol.asyncIterator](): ReadableStreamAsyncIterator<R>;
}
const ReadableStream: {
prototype: ReadableStream;
@@ -202,7 +205,12 @@ declare module "stream/web" {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */
interface ReadableStreamBYOBReader extends ReadableStreamGenericReader {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */
read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;
read<T extends ArrayBufferView>(
view: T,
options?: {
min?: number;
},
): Promise<ReadableStreamReadResult<T>>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */
releaseLock(): void;
}
@@ -299,9 +307,9 @@ declare module "stream/web" {
* sink.
*/
interface WritableStreamDefaultWriter<W = any> {
readonly closed: Promise<undefined>;
readonly closed: Promise<void>;
readonly desiredSize: number | null;
readonly ready: Promise<undefined>;
readonly ready: Promise<void>;
abort(reason?: any): Promise<void>;
close(): Promise<void>;
releaseLock(): void;
@@ -418,7 +426,7 @@ declare module "stream/web" {
global {
interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {}
/**
* `ByteLengthQueuingStrategy` class is a global reference for `require('stream/web').ByteLengthQueuingStrategy`.
* `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy
* @since v18.0.0
*/
@@ -428,7 +436,7 @@ declare module "stream/web" {
interface CompressionStream extends _CompressionStream {}
/**
* `CompressionStream` class is a global reference for `require('stream/web').CompressionStream`.
* `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-compressionstream
* @since v18.0.0
*/
@@ -448,7 +456,7 @@ declare module "stream/web" {
interface CountQueuingStrategy extends _CountQueuingStrategy {}
/**
* `CountQueuingStrategy` class is a global reference for `require('stream/web').CountQueuingStrategy`.
* `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-countqueuingstrategy
* @since v18.0.0
*/
@@ -457,7 +465,7 @@ declare module "stream/web" {
interface DecompressionStream extends _DecompressionStream {}
/**
* `DecompressionStream` class is a global reference for `require('stream/web').DecompressionStream`.
* `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-decompressionstream
* @since v18.0.0
*/
@@ -477,7 +485,7 @@ declare module "stream/web" {
interface ReadableByteStreamController extends _ReadableByteStreamController {}
/**
* `ReadableByteStreamController` class is a global reference for `require('stream/web').ReadableByteStreamController`.
* `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-readablebytestreamcontroller
* @since v18.0.0
*/
@@ -487,7 +495,7 @@ declare module "stream/web" {
interface ReadableStream<R = any> extends _ReadableStream<R> {}
/**
* `ReadableStream` class is a global reference for `require('stream/web').ReadableStream`.
* `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-readablestream
* @since v18.0.0
*/
@@ -496,7 +504,7 @@ declare module "stream/web" {
interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {}
/**
* `ReadableStreamBYOBReader` class is a global reference for `require('stream/web').ReadableStreamBYOBReader`.
* `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-readablestreambyobreader
* @since v18.0.0
*/
@@ -506,7 +514,7 @@ declare module "stream/web" {
interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {}
/**
* `ReadableStreamBYOBRequest` class is a global reference for `require('stream/web').ReadableStreamBYOBRequest`.
* `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-readablestreambyobrequest
* @since v18.0.0
*/
@@ -516,7 +524,7 @@ declare module "stream/web" {
interface ReadableStreamDefaultController<R = any> extends _ReadableStreamDefaultController<R> {}
/**
* `ReadableStreamDefaultController` class is a global reference for `require('stream/web').ReadableStreamDefaultController`.
* `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller
* @since v18.0.0
*/
@@ -526,7 +534,7 @@ declare module "stream/web" {
interface ReadableStreamDefaultReader<R = any> extends _ReadableStreamDefaultReader<R> {}
/**
* `ReadableStreamDefaultReader` class is a global reference for `require('stream/web').ReadableStreamDefaultReader`.
* `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-readablestreamdefaultreader
* @since v18.0.0
*/
@@ -536,7 +544,7 @@ declare module "stream/web" {
interface TextDecoderStream extends _TextDecoderStream {}
/**
* `TextDecoderStream` class is a global reference for `require('stream/web').TextDecoderStream`.
* `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-textdecoderstream
* @since v18.0.0
*/
@@ -545,7 +553,7 @@ declare module "stream/web" {
interface TextEncoderStream extends _TextEncoderStream {}
/**
* `TextEncoderStream` class is a global reference for `require('stream/web').TextEncoderStream`.
* `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-textencoderstream
* @since v18.0.0
*/
@@ -554,7 +562,7 @@ declare module "stream/web" {
interface TransformStream<I = any, O = any> extends _TransformStream<I, O> {}
/**
* `TransformStream` class is a global reference for `require('stream/web').TransformStream`.
* `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-transformstream
* @since v18.0.0
*/
@@ -563,7 +571,7 @@ declare module "stream/web" {
interface TransformStreamDefaultController<O = any> extends _TransformStreamDefaultController<O> {}
/**
* `TransformStreamDefaultController` class is a global reference for `require('stream/web').TransformStreamDefaultController`.
* `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller
* @since v18.0.0
*/
@@ -573,7 +581,7 @@ declare module "stream/web" {
interface WritableStream<W = any> extends _WritableStream<W> {}
/**
* `WritableStream` class is a global reference for `require('stream/web').WritableStream`.
* `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-writablestream
* @since v18.0.0
*/
@@ -582,7 +590,7 @@ declare module "stream/web" {
interface WritableStreamDefaultController extends _WritableStreamDefaultController {}
/**
* `WritableStreamDefaultController` class is a global reference for `require('stream/web').WritableStreamDefaultController`.
* `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller
* @since v18.0.0
*/
@@ -592,7 +600,7 @@ declare module "stream/web" {
interface WritableStreamDefaultWriter<W = any> extends _WritableStreamDefaultWriter<W> {}
/**
* `WritableStreamDefaultWriter` class is a global reference for `require('stream/web').WritableStreamDefaultWriter`.
* `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter
* @since v18.0.0
*/

View File

@@ -4,13 +4,13 @@
* characters. It can be accessed using:
*
* ```js
* const { StringDecoder } = require('node:string_decoder');
* import { StringDecoder } from 'node:string_decoder';
* ```
*
* The following example shows the basic use of the `StringDecoder` class.
*
* ```js
* const { StringDecoder } = require('node:string_decoder');
* import { StringDecoder } from 'node:string_decoder';
* const decoder = new StringDecoder('utf8');
*
* const cent = Buffer.from([0xC2, 0xA2]);
@@ -29,14 +29,14 @@
* symbol (`€`) are written over three separate operations:
*
* ```js
* const { StringDecoder } = require('node:string_decoder');
* import { StringDecoder } from 'node:string_decoder';
* const decoder = new StringDecoder('utf8');
*
* decoder.write(Buffer.from([0xE2]));
* decoder.write(Buffer.from([0x82]));
* console.log(decoder.end(Buffer.from([0xAC]))); // Prints: €
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/string_decoder.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/string_decoder.js)
*/
declare module "string_decoder" {
class StringDecoder {

497
node_modules/@types/node/test.d.ts generated vendored
View File

@@ -10,7 +10,7 @@
* work:
*
* ```js
* import test from 'test';
* import test from 'node:test';
* ```
*
* Tests created via the `test` module consist of a single function that is
@@ -76,7 +76,7 @@
*
* If any tests fail, the process exit code is set to `1`.
* @since v18.0.0, v16.17.0
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js)
*/
declare module "node:test" {
import { Readable } from "node:stream";
@@ -147,6 +147,7 @@ declare module "node:test" {
export {
after,
afterEach,
assert,
before,
beforeEach,
describe,
@@ -319,9 +320,17 @@ declare module "node:test" {
* @default false
*/
concurrency?: number | boolean | undefined;
/**
* Specifies the current working directory to be used by the test runner.
* Serves as the base path for resolving files according to the
* [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model).
* @since v23.0.0
* @default process.cwd()
*/
cwd?: string | undefined;
/**
* An array containing the list of files to run. If omitted, files are run according to the
* [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model).
* [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model).
*/
files?: readonly string[] | undefined;
/**
@@ -331,13 +340,31 @@ declare module "node:test" {
* @default false
*/
forceExit?: boolean | undefined;
/**
* An array containing the list of glob patterns to match test files.
* This option cannot be used together with `files`. If omitted, files are run according to the
* [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model).
* @since v22.6.0
*/
globPatterns?: readonly string[] | undefined;
/**
* Sets inspector port of test child process.
* If a nullish value is provided, each process gets its own port,
* incremented from the primary's `process.debugPort`.
* This can be a number, or a function that takes no arguments and returns a
* number. If a nullish value is provided, each process gets its own port,
* incremented from the primary's `process.debugPort`. This option is ignored
* if the `isolation` option is set to `'none'` as no child processes are
* spawned.
* @default undefined
*/
inspectPort?: number | (() => number) | undefined;
/**
* Configures the type of test isolation. If set to
* `'process'`, each test file is run in a separate child process. If set to
* `'none'`, all test files run in the current process.
* @default 'process'
* @since v22.8.0
*/
isolation?: "process" | "none" | undefined;
/**
* If truthy, the test context will only run tests that have the `only` option set
*/
@@ -347,6 +374,20 @@ declare module "node:test" {
* @default undefined
*/
setup?: ((reporter: TestsStream) => void | Promise<void>) | undefined;
/**
* An array of CLI flags to pass to the `node` executable when
* spawning the subprocesses. This option has no effect when `isolation` is `'none`'.
* @since v22.10.0
* @default []
*/
execArgv?: readonly string[] | undefined;
/**
* An array of CLI flags to pass to each test file when spawning the
* subprocesses. This option has no effect when `isolation` is `'none'`.
* @since v22.10.0
* @default []
*/
argv?: readonly string[] | undefined;
/**
* Allows aborting an in-progress test execution.
*/
@@ -382,6 +423,53 @@ declare module "node:test" {
* @default undefined
*/
shard?: TestShard | undefined;
/**
* enable [code coverage](https://nodejs.org/docs/latest-v24.x/api/test.html#collecting-code-coverage) collection.
* @since v22.10.0
* @default false
*/
coverage?: boolean | undefined;
/**
* Excludes specific files from code coverage
* using a glob pattern, which can match both absolute and relative file paths.
* This property is only applicable when `coverage` was set to `true`.
* If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided,
* files must meet **both** criteria to be included in the coverage report.
* @since v22.10.0
* @default undefined
*/
coverageExcludeGlobs?: string | readonly string[] | undefined;
/**
* Includes specific files in code coverage
* using a glob pattern, which can match both absolute and relative file paths.
* This property is only applicable when `coverage` was set to `true`.
* If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided,
* files must meet **both** criteria to be included in the coverage report.
* @since v22.10.0
* @default undefined
*/
coverageIncludeGlobs?: string | readonly string[] | undefined;
/**
* Require a minimum percent of covered lines. If code
* coverage does not reach the threshold specified, the process will exit with code `1`.
* @since v22.10.0
* @default 0
*/
lineCoverage?: number | undefined;
/**
* Require a minimum percent of covered branches. If code
* coverage does not reach the threshold specified, the process will exit with code `1`.
* @since v22.10.0
* @default 0
*/
branchCoverage?: number | undefined;
/**
* Require a minimum percent of covered functions. If code
* coverage does not reach the threshold specified, the process will exit with code `1`.
* @since v22.10.0
* @default 0
*/
functionCoverage?: number | undefined;
}
/**
* A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.
@@ -401,6 +489,7 @@ declare module "node:test" {
addListener(event: "test:start", listener: (data: TestStart) => void): this;
addListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
addListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
addListener(event: "test:summary", listener: (data: TestSummary) => void): this;
addListener(event: "test:watch:drained", listener: () => void): this;
addListener(event: string, listener: (...args: any[]) => void): this;
emit(event: "test:coverage", data: TestCoverage): boolean;
@@ -414,6 +503,7 @@ declare module "node:test" {
emit(event: "test:start", data: TestStart): boolean;
emit(event: "test:stderr", data: TestStderr): boolean;
emit(event: "test:stdout", data: TestStdout): boolean;
emit(event: "test:summary", data: TestSummary): boolean;
emit(event: "test:watch:drained"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "test:coverage", listener: (data: TestCoverage) => void): this;
@@ -427,6 +517,7 @@ declare module "node:test" {
on(event: "test:start", listener: (data: TestStart) => void): this;
on(event: "test:stderr", listener: (data: TestStderr) => void): this;
on(event: "test:stdout", listener: (data: TestStdout) => void): this;
on(event: "test:summary", listener: (data: TestSummary) => void): this;
on(event: "test:watch:drained", listener: () => void): this;
on(event: string, listener: (...args: any[]) => void): this;
once(event: "test:coverage", listener: (data: TestCoverage) => void): this;
@@ -440,6 +531,7 @@ declare module "node:test" {
once(event: "test:start", listener: (data: TestStart) => void): this;
once(event: "test:stderr", listener: (data: TestStderr) => void): this;
once(event: "test:stdout", listener: (data: TestStdout) => void): this;
once(event: "test:summary", listener: (data: TestSummary) => void): this;
once(event: "test:watch:drained", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this;
@@ -453,6 +545,7 @@ declare module "node:test" {
prependListener(event: "test:start", listener: (data: TestStart) => void): this;
prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
prependListener(event: "test:summary", listener: (data: TestSummary) => void): this;
prependListener(event: "test:watch:drained", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this;
@@ -466,6 +559,7 @@ declare module "node:test" {
prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this;
prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
prependOnceListener(event: "test:summary", listener: (data: TestSummary) => void): this;
prependOnceListener(event: "test:watch:drained", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
}
@@ -479,7 +573,24 @@ declare module "node:test" {
/**
* An object containing assertion methods bound to the test context.
* The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans.
* @since v22.2.0
*
* **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the
* TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed**
* (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler:
* ```ts
* import { test, type TestContext } from 'node:test';
*
* // The test function's context parameter must have a type annotation.
* test('example', (t: TestContext) => {
* t.assert.deepStrictEqual(actual, expected);
* });
*
* // Omitting the type annotation will result in a compilation error.
* test('example', t => {
* t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation.
* });
* ```
* @since v22.2.0, v20.15.0
*/
readonly assert: TestContextAssert;
/**
@@ -528,6 +639,12 @@ declare module "node:test" {
* @param message Message to be reported.
*/
diagnostic(message: string): void;
/**
* The absolute path of the test file that created the current test. If a test file imports
* additional modules that generate tests, the imported tests will return the path of the root test file.
* @since v22.6.0
*/
readonly filePath: string | undefined;
/**
* The name of the test and each of its ancestors, separated by `>`.
* @since v22.3.0
@@ -539,11 +656,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);
@@ -552,7 +670,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() {
@@ -566,14 +686,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
@@ -645,80 +786,73 @@ declare module "node:test" {
* @returns A {@link Promise} resolved with `undefined` once the test completes.
*/
test: typeof test;
/**
* This method polls a `condition` function until that function either returns
* successfully or the operation times out.
* @since v22.14.0
* @param condition An assertion function that is invoked
* periodically until it completes successfully or the defined polling timeout
* elapses. Successful completion is defined as not throwing or rejecting. This
* function does not accept any arguments, and is allowed to return any value.
* @param options An optional configuration object for the polling operation.
* @returns Fulfilled with the value returned by `condition`.
*/
waitFor<T>(condition: () => T, options?: TestContextWaitForOptions): Promise<Awaited<T>>;
/**
* Each test provides its own MockTracker instance.
*/
readonly mock: MockTracker;
}
interface TestContextAssert {
interface TestContextAssert extends
Pick<
typeof import("assert"),
| "deepEqual"
| "deepStrictEqual"
| "doesNotMatch"
| "doesNotReject"
| "doesNotThrow"
| "equal"
| "fail"
| "ifError"
| "match"
| "notDeepEqual"
| "notDeepStrictEqual"
| "notEqual"
| "notStrictEqual"
| "ok"
| "partialDeepStrictEqual"
| "rejects"
| "strictEqual"
| "throws"
>
{
/**
* Identical to the `deepEqual` function from the `node:assert` module, but bound to the test context.
* This function serializes `value` and writes it to the file specified by `path`.
*
* ```js
* test('snapshot test with default serialization', (t) => {
* t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json');
* });
* ```
*
* This function differs from `context.assert.snapshot()` in the following ways:
*
* * The snapshot file path is explicitly provided by the user.
* * Each snapshot file is limited to a single snapshot value.
* * No additional escaping is performed by the test runner.
*
* These differences allow snapshot files to better support features such as syntax
* highlighting.
* @since v22.14.0
* @param value A value to serialize to a string. If Node.js was started with
* the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots)
* flag, the serialized value is written to
* `path`. Otherwise, the serialized value is compared to the contents of the
* existing snapshot file.
* @param path The file where the serialized `value` is written.
* @param options Optional configuration options.
*/
deepEqual: typeof import("node:assert").deepEqual;
/**
* Identical to the `deepStrictEqual` function from the `node:assert` module, but bound to the test context.
*/
deepStrictEqual: typeof import("node:assert").deepStrictEqual;
/**
* Identical to the `doesNotMatch` function from the `node:assert` module, but bound to the test context.
*/
doesNotMatch: typeof import("node:assert").doesNotMatch;
/**
* Identical to the `doesNotReject` function from the `node:assert` module, but bound to the test context.
*/
doesNotReject: typeof import("node:assert").doesNotReject;
/**
* Identical to the `doesNotThrow` function from the `node:assert` module, but bound to the test context.
*/
doesNotThrow: typeof import("node:assert").doesNotThrow;
/**
* Identical to the `equal` function from the `node:assert` module, but bound to the test context.
*/
equal: typeof import("node:assert").equal;
/**
* Identical to the `fail` function from the `node:assert` module, but bound to the test context.
*/
fail: typeof import("node:assert").fail;
/**
* Identical to the `ifError` function from the `node:assert` module, but bound to the test context.
*/
ifError: typeof import("node:assert").ifError;
/**
* Identical to the `match` function from the `node:assert` module, but bound to the test context.
*/
match: typeof import("node:assert").match;
/**
* Identical to the `notDeepEqual` function from the `node:assert` module, but bound to the test context.
*/
notDeepEqual: typeof import("node:assert").notDeepEqual;
/**
* Identical to the `notDeepStrictEqual` function from the `node:assert` module, but bound to the test context.
*/
notDeepStrictEqual: typeof import("node:assert").notDeepStrictEqual;
/**
* Identical to the `notEqual` function from the `node:assert` module, but bound to the test context.
*/
notEqual: typeof import("node:assert").notEqual;
/**
* Identical to the `notStrictEqual` function from the `node:assert` module, but bound to the test context.
*/
notStrictEqual: typeof import("node:assert").notStrictEqual;
/**
* Identical to the `ok` function from the `node:assert` module, but bound to the test context.
*/
ok: typeof import("node:assert").ok;
/**
* Identical to the `rejects` function from the `node:assert` module, but bound to the test context.
*/
rejects: typeof import("node:assert").rejects;
/**
* Identical to the `strictEqual` function from the `node:assert` module, but bound to the test context.
*/
strictEqual: typeof import("node:assert").strictEqual;
/**
* Identical to the `throws` function from the `node:assert` module, but bound to the test context.
*/
throws: typeof import("node:assert").throws;
fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void;
/**
* This function implements assertions for snapshot testing.
* ```js
@@ -732,12 +866,18 @@ declare module "node:test" {
* });
* });
* ```
*
* Only available through the [--experimental-test-snapshots](https://nodejs.org/api/cli.html#--experimental-test-snapshots) flag.
* @since v22.3.0
* @experimental
* @param value A value to serialize to a string. If Node.js was started with
* the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots)
* flag, the serialized value is written to
* the snapshot file. Otherwise, the serialized value is compared to the
* corresponding value in the existing snapshot file.
*/
snapshot(value: any, options?: AssertSnapshotOptions): void;
/**
* A custom assertion function registered with `assert.register()`.
*/
[name: string]: (...args: any[]) => void;
}
interface AssertSnapshotOptions {
/**
@@ -750,6 +890,34 @@ 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
* invocation of `condition` before trying again.
* @default 50
*/
interval?: number | undefined;
/**
* The poll timeout in milliseconds. If `condition` has not
* succeeded by the time this elapses, an error occurs.
* @default 1000
*/
timeout?: number | undefined;
}
/**
* An instance of `SuiteContext` is passed to each suite function in order to
@@ -758,6 +926,12 @@ declare module "node:test" {
* @since v18.7.0, v16.17.0
*/
class SuiteContext {
/**
* The absolute path of the test file that created the current suite. If a test file imports
* additional modules that generate suites, the imported suites will return the path of the root test file.
* @since v22.6.0
*/
readonly filePath: string | undefined;
/**
* The name of the suite.
* @since v18.8.0, v16.18.0
@@ -1126,10 +1300,43 @@ declare module "node:test" {
): Mock<((value: MockedObject[MethodName]) => void) | Implementation>;
/**
* This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules.
* Any references to the original module prior to mocking are not impacted.
* This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and
* Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In
* order to enable module mocking, Node.js must be started with the
* [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-module-mocks)
* command-line flag.
*
* Only available through the [--experimental-test-module-mocks](https://nodejs.org/api/cli.html#--experimental-test-module-mocks) flag.
* 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
* // does not exist in the original 'node:readline' module.
* const mock = t.mock.module('node:readline', {
* namedExports: { fn() { return 42; } },
* });
*
* let esmImpl = await import('node:readline');
* let cjsImpl = require('node:readline');
*
* // cursorTo() is an export of the original 'node:readline' module.
* assert.strictEqual(esmImpl.cursorTo, undefined);
* assert.strictEqual(cjsImpl.cursorTo, undefined);
* assert.strictEqual(esmImpl.fn(), 42);
* assert.strictEqual(cjsImpl.fn(), 42);
*
* mock.restore();
*
* // The mock is restored, so the original builtin module is returned.
* esmImpl = await import('node:readline');
* cjsImpl = require('node:readline');
*
* assert.strictEqual(typeof esmImpl.cursorTo, 'function');
* assert.strictEqual(typeof cjsImpl.cursorTo, 'function');
* assert.strictEqual(esmImpl.fn, undefined);
* assert.strictEqual(cjsImpl.fn, undefined);
* });
* ```
* @since v22.3.0
* @experimental
* @param specifier A string identifying the module to mock.
@@ -1324,7 +1531,6 @@ declare module "node:test" {
* The `MockTracker` provides a top-level `timers` export
* which is a `MockTimers` instance.
* @since v20.4.0
* @experimental
*/
class MockTimers {
/**
@@ -1530,9 +1736,25 @@ declare module "node:test" {
[Symbol.dispose](): void;
}
/**
* Only available through the [--experimental-test-snapshots](https://nodejs.org/api/cli.html#--experimental-test-snapshots) flag.
* An object whose methods are used to configure available assertions on the
* `TestContext` objects in the current process. The methods from `node:assert`
* and snapshot testing functions are available by default.
*
* It is possible to apply the same configuration to all files by placing common
* configuration code in a module
* preloaded with `--require` or `--import`.
* @since v22.14.0
*/
namespace assert {
/**
* Defines a new assertion function with the provided name and function. If an
* assertion already exists with the same name, it is overwritten.
* @since v22.14.0
*/
function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void;
}
/**
* @since v22.3.0
* @experimental
*/
namespace snapshot {
/**
@@ -1552,15 +1774,17 @@ declare module "node:test" {
* This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing.
* By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended.
* @since v22.3.0
* @param fn A function which returns a string specifying the location of the snapshot file.
* The function receives the path of the test file as its only argument.
* If `process.argv[1]` is not associated with a file (for example in the REPL), the input is undefined.
* @param fn A function used to compute the location of the snapshot file.
* The function receives the path of the test file as its only argument. If the
* test is not associated with a file (for example in the REPL), the input is
* undefined. `fn()` must return a string specifying the location of the snapshot file.
*/
function setResolveSnapshotPath(fn: (path: string | undefined) => string): void;
}
export {
after,
afterEach,
assert,
before,
beforeEach,
describe,
@@ -1701,6 +1925,25 @@ interface TestCoverage {
count: number;
}>;
}>;
/**
* An object containing whether or not the coverage for
* each coverage type.
* @since v22.9.0
*/
thresholds: {
/**
* The function coverage threshold.
*/
function: number;
/**
* The branch coverage threshold.
*/
branch: number;
/**
* The line coverage threshold.
*/
line: number;
};
/**
* An object containing a summary of coverage for all files.
*/
@@ -1806,6 +2049,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 {
/**
@@ -1816,6 +2064,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 {
/**
@@ -1933,6 +2186,57 @@ interface TestStdout {
*/
message: string;
}
interface TestSummary {
/**
* An object containing the counts of various test results.
*/
counts: {
/**
* The total number of cancelled tests.
*/
cancelled: number;
/**
* The total number of passed tests.
*/
passed: number;
/**
* The total number of skipped tests.
*/
skipped: number;
/**
* The total number of suites run.
*/
suites: number;
/**
* The total number of tests run, excluding suites.
*/
tests: number;
/**
* The total number of TODO tests.
*/
todo: number;
/**
* The total number of top level tests and suites.
*/
topLevel: number;
};
/**
* The duration of the test run in milliseconds.
*/
duration_ms: number;
/**
* The path of the test file that generated the
* summary. If the summary corresponds to multiple files, this value is
* `undefined`.
*/
file: string | undefined;
/**
* Indicates whether or not the test run is considered
* successful or not. If any error condition occurs, such as a failing test or
* unmet coverage threshold, this value will be set to `false`.
*/
success: boolean;
}
/**
* The `node:test/reporters` module exposes the builtin-reporters for `node:test`.
@@ -1946,10 +2250,10 @@ interface TestStdout {
* work:
*
* ```js
* import test from 'test/reporters';
* import test from 'node:test/reporters';
* ```
* @since v19.9.0
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test/reporters.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test/reporters.js)
*/
declare module "node:test/reporters" {
import { Transform, TransformOptions } from "node:stream";
@@ -1966,6 +2270,7 @@ declare module "node:test/reporters" {
| { type: "test:start"; data: TestStart }
| { type: "test:stderr"; data: TestStderr }
| { type: "test:stdout"; data: TestStdout }
| { type: "test:summary"; data: TestSummary }
| { type: "test:watch:drained"; data: undefined };
type TestEventGenerator = AsyncGenerator<TestEvent, void>;
@@ -2004,12 +2309,10 @@ declare module "node:test/reporters" {
}
/**
* The `lcov` reporter outputs test coverage when used with the
* [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag.
* [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-coverage) flag.
* @since v22.0.0
*/
// TODO: change the export to a wrapper function once node@0db38f0 is merged (breaking change)
// const lcov: ReporterConstructorWrapper<typeof LcovReporter>;
const lcov: LcovReporter;
const lcov: ReporterConstructorWrapper<typeof LcovReporter>;
export { dot, junit, lcov, spec, tap, TestEvent };
}

305
node_modules/@types/node/timers.d.ts generated vendored
View File

@@ -1,21 +1,17 @@
/**
* The `timer` module exposes a global API for scheduling functions to
* be called at some future period of time. Because the timer functions are
* globals, there is no need to call `require('node:timers')` to use the API.
* globals, there is no need to import `node:timers` to use the API.
*
* The timer functions within Node.js implement a similar API as the timers API
* provided by Web Browsers but use a different internal implementation that is
* built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout).
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js)
*/
declare module "timers" {
import { Abortable } from "node:events";
import {
setImmediate as setImmediatePromise,
setInterval as setIntervalPromise,
setTimeout as setTimeoutPromise,
} from "node:timers/promises";
interface TimerOptions extends Abortable {
import * as promises from "node:timers/promises";
export interface TimerOptions extends Abortable {
/**
* Set to `false` to indicate that the scheduled `Timeout`
* should not require the Node.js event loop to remain active.
@@ -23,38 +19,33 @@ declare module "timers" {
*/
ref?: boolean | undefined;
}
let setTimeout: typeof global.setTimeout;
let clearTimeout: typeof global.clearTimeout;
let setInterval: typeof global.setInterval;
let clearInterval: typeof global.clearInterval;
let setImmediate: typeof global.setImmediate;
let clearImmediate: typeof global.clearImmediate;
global {
namespace NodeJS {
// compatibility with older typings
interface Timer extends RefCounted {
hasRef(): boolean;
refresh(): this;
[Symbol.toPrimitive](): number;
}
/**
* This object is created internally and is returned from `setImmediate()`. It
* can be passed to `clearImmediate()` in order to cancel the scheduled
* actions.
*
* By default, when an immediate is scheduled, the Node.js event loop will continue
* running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to
* control this default behavior.
* running as long as the immediate is active. The `Immediate` object returned by
* `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`
* functions that can be used to control this default behavior.
*/
class Immediate implements RefCounted {
interface Immediate extends RefCounted, Disposable {
/**
* When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no
* If true, the `Immediate` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
/**
* When called, requests that the Node.js event loop _not_ exit so long as the
* `Immediate` is active. Calling `immediate.ref()` multiple times will have no
* effect.
*
* By default, all `Immediate` objects are "ref'ed", making it normally unnecessary
* to call `immediate.ref()` unless `immediate.unref()` had been called previously.
* @since v9.7.0
* @return a reference to `immediate`
* @returns a reference to `immediate`
*/
ref(): this;
/**
@@ -63,53 +54,59 @@ declare module "timers" {
* running, the process may exit before the `Immediate` object's callback is
* invoked. Calling `immediate.unref()` multiple times will have no effect.
* @since v9.7.0
* @return a reference to `immediate`
* @returns a reference to `immediate`
*/
unref(): this;
/**
* If true, the `Immediate` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
_onImmediate: Function; // to distinguish it from the Timeout class
/**
* Cancels the immediate. This is similar to calling `clearImmediate()`.
* @since v20.5.0
* @since v20.5.0, v18.18.0
* @experimental
*/
[Symbol.dispose](): void;
_onImmediate(...args: any[]): void;
}
// Legacy interface used in Node.js v9 and prior
// TODO: remove in a future major version bump
/** @deprecated Use `NodeJS.Timeout` instead. */
interface Timer extends RefCounted {
hasRef(): boolean;
refresh(): this;
[Symbol.toPrimitive](): number;
}
/**
* This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the
* scheduled actions.
* This object is created internally and is returned from `setTimeout()` and
* `setInterval()`. It can be passed to either `clearTimeout()` or
* `clearInterval()` in order to cancel the scheduled actions.
*
* By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the
* By default, when a timer is scheduled using either `setTimeout()` or
* `setInterval()`, the Node.js event loop will continue running as long as the
* timer is active. Each of the `Timeout` objects returned by these functions
* export both `timeout.ref()` and `timeout.unref()` functions that can be used to
* control this default behavior.
*/
class Timeout implements Timer {
interface Timeout extends RefCounted, Disposable, Timer {
/**
* When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
*
* By default, all `Timeout` objects are "ref'ed", making it normally unnecessary
* to call `timeout.ref()` unless `timeout.unref()` had been called previously.
* Cancels the timeout.
* @since v0.9.1
* @return a reference to `timeout`
* @legacy Use `clearTimeout()` instead.
* @returns a reference to `timeout`
*/
ref(): this;
/**
* When called, the active `Timeout` object will not require the Node.js event loop
* to remain active. If there is no other activity keeping the event loop running,
* the process may exit before the `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect.
* @since v0.9.1
* @return a reference to `timeout`
*/
unref(): this;
close(): this;
/**
* If true, the `Timeout` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
/**
* When called, requests that the Node.js event loop _not_ exit so long as the
* `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
*
* By default, all `Timeout` objects are "ref'ed", making it normally unnecessary
* to call `timeout.ref()` unless `timeout.unref()` had been called previously.
* @since v0.9.1
* @returns a reference to `timeout`
*/
ref(): this;
/**
* Sets the timer's start time to the current time, and reschedules the timer to
* call its callback at the previously specified duration adjusted to the current
@@ -119,85 +116,37 @@ declare module "timers" {
* Using this on a timer that has already called its callback will reactivate the
* timer.
* @since v10.2.0
* @return a reference to `timeout`
* @returns a reference to `timeout`
*/
refresh(): this;
/**
* When called, the active `Timeout` object will not require the Node.js event loop
* to remain active. If there is no other activity keeping the event loop running,
* the process may exit before the `Timeout` object's callback is invoked. Calling
* `timeout.unref()` multiple times will have no effect.
* @since v0.9.1
* @returns a reference to `timeout`
*/
unref(): this;
/**
* Coerce a `Timeout` to a primitive. The primitive can be used to
* clear the `Timeout`. The primitive can only be used in the
* same thread where the timeout was created. Therefore, to use it
* across `worker_threads` it must first be passed to the correct
* thread. This allows enhanced compatibility with browser
* `setTimeout()` and `setInterval()` implementations.
* @since v14.9.0, v12.19.0
*/
[Symbol.toPrimitive](): number;
/**
* Cancels the timeout.
* @since v20.5.0
* @since v20.5.0, v18.18.0
* @experimental
*/
[Symbol.dispose](): void;
_onTimeout(...args: any[]): void;
}
}
/**
* Schedules execution of a one-time `callback` after `delay` milliseconds.
*
* The `callback` will likely not be invoked in precisely `delay` milliseconds.
* Node.js makes no guarantees about the exact timing of when callbacks will fire,
* nor of their ordering. The callback will be called as close as possible to the
* time specified.
*
* When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
* @since v0.0.1
* @param callback The function to call when the timer elapses.
* @param [delay=1] The number of milliseconds to wait before calling the `callback`.
* @param args Optional arguments to pass when the `callback` is called.
* @return for use with {@link clearTimeout}
*/
function setTimeout<TArgs extends any[]>(
callback: (...args: TArgs) => void,
ms?: number,
...args: TArgs
): NodeJS.Timeout;
// util.promisify no rest args compability
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout;
namespace setTimeout {
const __promisify__: typeof setTimeoutPromise;
}
/**
* Cancels a `Timeout` object created by `setTimeout()`.
* @since v0.0.1
* @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number.
*/
function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void;
/**
* Schedules repeated execution of `callback` every `delay` milliseconds.
*
* When `delay` is larger than `2147483647` or less than `1`, the `delay` will be
* set to `1`. Non-integer delays are truncated to an integer.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using `timersPromises.setInterval()`.
* @since v0.0.1
* @param callback The function to call when the timer elapses.
* @param [delay=1] The number of milliseconds to wait before calling the `callback`.
* @param args Optional arguments to pass when the `callback` is called.
* @return for use with {@link clearInterval}
*/
function setInterval<TArgs extends any[]>(
callback: (...args: TArgs) => void,
ms?: number,
...args: TArgs
): NodeJS.Timeout;
// util.promisify no rest args compability
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout;
namespace setInterval {
const __promisify__: typeof setIntervalPromise;
}
/**
* Cancels a `Timeout` object created by `setInterval()`.
* @since v0.0.1
* @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number.
*/
function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void;
/**
* Schedules the "immediate" execution of the `callback` after I/O events'
* callbacks.
@@ -210,30 +159,128 @@ declare module "timers" {
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using `timersPromises.setImmediate()`.
* This method has a custom variant for promises that is available using
* `timersPromises.setImmediate()`.
* @since v0.9.1
* @param callback The function to call at the end of this turn of the Node.js `Event Loop`
* @param callback The function to call at the end of this turn of
* the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout)
* @param args Optional arguments to pass when the `callback` is called.
* @return for use with {@link clearImmediate}
* @returns for use with `clearImmediate()`
*/
function setImmediate<TArgs extends any[]>(
callback: (...args: TArgs) => void,
...args: TArgs
): NodeJS.Immediate;
// util.promisify no rest args compability
// Allow a single void-accepting argument to be optional in arguments lists.
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setImmediate(callback: (args: void) => void): NodeJS.Immediate;
function setImmediate(callback: (_: void) => void): NodeJS.Immediate;
namespace setImmediate {
const __promisify__: typeof setImmediatePromise;
import __promisify__ = promises.setImmediate;
export { __promisify__ };
}
/**
* Schedules repeated execution of `callback` every `delay` milliseconds.
*
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
* will be set to `1`. Non-integer delays are truncated to an integer.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using
* `timersPromises.setInterval()`.
* @since v0.0.1
* @param callback The function to call when the timer elapses.
* @param delay The number of milliseconds to wait before calling the
* `callback`. **Default:** `1`.
* @param args Optional arguments to pass when the `callback` is called.
* @returns for use with `clearInterval()`
*/
function setInterval<TArgs extends any[]>(
callback: (...args: TArgs) => void,
delay?: number,
...args: TArgs
): NodeJS.Timeout;
// Allow a single void-accepting argument to be optional in arguments lists.
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
/**
* Schedules execution of a one-time `callback` after `delay` milliseconds.
*
* The `callback` will likely not be invoked in precisely `delay` milliseconds.
* Node.js makes no guarantees about the exact timing of when callbacks will fire,
* nor of their ordering. The callback will be called as close as possible to the
* time specified.
*
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
* will be set to `1`. Non-integer delays are truncated to an integer.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using
* `timersPromises.setTimeout()`.
* @since v0.0.1
* @param callback The function to call when the timer elapses.
* @param delay The number of milliseconds to wait before calling the
* `callback`. **Default:** `1`.
* @param args Optional arguments to pass when the `callback` is called.
* @returns for use with `clearTimeout()`
*/
function setTimeout<TArgs extends any[]>(
callback: (...args: TArgs) => void,
delay?: number,
...args: TArgs
): NodeJS.Timeout;
// Allow a single void-accepting argument to be optional in arguments lists.
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
namespace setTimeout {
import __promisify__ = promises.setTimeout;
export { __promisify__ };
}
/**
* Cancels an `Immediate` object created by `setImmediate()`.
* @since v0.9.1
* @param immediate An `Immediate` object as returned by {@link setImmediate}.
* @param immediate An `Immediate` object as returned by `setImmediate()`.
*/
function clearImmediate(immediate: NodeJS.Immediate | undefined): void;
/**
* Cancels a `Timeout` object created by `setInterval()`.
* @since v0.0.1
* @param timeout A `Timeout` object as returned by `setInterval()`
* or the primitive of the `Timeout` object as a string or a number.
*/
function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void;
/**
* Cancels a `Timeout` object created by `setTimeout()`.
* @since v0.0.1
* @param timeout A `Timeout` object as returned by `setTimeout()`
* or the primitive of the `Timeout` object as a string or a number.
*/
function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void;
/**
* The `queueMicrotask()` method queues a microtask to invoke `callback`. If
* `callback` throws an exception, the `process` object `'uncaughtException'`
* event will be emitted.
*
* The microtask queue is managed by V8 and may be used in a similar manner to
* the `process.nextTick()` queue, which is managed by Node.js. The
* `process.nextTick()` queue is always processed before the microtask queue
* within each turn of the Node.js event loop.
* @since v11.0.0
* @param callback Function to be queued.
*/
function clearImmediate(immediateId: NodeJS.Immediate | undefined): void;
function queueMicrotask(callback: () => void): void;
}
import clearImmediate = globalThis.clearImmediate;
import clearInterval = globalThis.clearInterval;
import clearTimeout = globalThis.clearTimeout;
import setImmediate = globalThis.setImmediate;
import setInterval = globalThis.setInterval;
import setTimeout = globalThis.setTimeout;
export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout };
}
declare module "node:timers" {
export * from "timers";

View File

@@ -1,15 +1,17 @@
/**
* The `timers/promises` API provides an alternative set of timer functions
* that return `Promise` objects. The API is accessible via `require('node:timers/promises')`.
* that return `Promise` objects. The API is accessible via
* `require('node:timers/promises')`.
*
* ```js
* import {
* setTimeout,
* setImmediate,
* setInterval,
* } from 'timers/promises';
* } from 'node:timers/promises';
* ```
* @since v15.0.0
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers/promises.js)
*/
declare module "timers/promises" {
import { TimerOptions } from "node:timers";
@@ -17,14 +19,15 @@ declare module "timers/promises" {
* ```js
* import {
* setTimeout,
* } from 'timers/promises';
* } from 'node:timers/promises';
*
* const res = await setTimeout(100, 'result');
*
* console.log(res); // Prints 'result'
* ```
* @since v15.0.0
* @param [delay=1] The number of milliseconds to wait before fulfilling the promise.
* @param delay The number of milliseconds to wait before fulfilling the
* promise. **Default:** `1`.
* @param value A value with which the promise is fulfilled.
*/
function setTimeout<T = void>(delay?: number, value?: T, options?: TimerOptions): Promise<T>;
@@ -32,7 +35,7 @@ declare module "timers/promises" {
* ```js
* import {
* setImmediate,
* } from 'timers/promises';
* } from 'node:timers/promises';
*
* const res = await setImmediate('result');
*
@@ -50,7 +53,7 @@ declare module "timers/promises" {
* ```js
* import {
* setInterval,
* } from 'timers/promises';
* } from 'node:timers/promises';
*
* const interval = 100;
* for await (const startTime of setInterval(interval, Date.now())) {
@@ -62,33 +65,41 @@ declare module "timers/promises" {
* console.log(Date.now());
* ```
* @since v15.9.0
* @param delay The number of milliseconds to wait between iterations.
* **Default:** `1`.
* @param value A value with which the iterator returns.
*/
function setInterval<T = void>(delay?: number, value?: T, options?: TimerOptions): AsyncIterable<T>;
function setInterval<T = void>(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator<T>;
interface Scheduler {
/**
* An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification being developed as a standard Web Platform API.
* An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification
* being developed as a standard Web Platform API.
*
* Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent to calling `timersPromises.setTimeout(delay, undefined, options)` except that the `ref`
* option is not supported.
* Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent
* to calling `timersPromises.setTimeout(delay, undefined, options)` except that
* the `ref` option is not supported.
*
* ```js
* import { scheduler } from 'node:timers/promises';
*
* await scheduler.wait(1000); // Wait one second before continuing
* ```
* @since v16.14.0
* @since v17.3.0, v16.14.0
* @experimental
* @param [delay=1] The number of milliseconds to wait before fulfilling the promise.
* @param delay The number of milliseconds to wait before resolving the
* promise.
*/
wait: (delay?: number, options?: Pick<TimerOptions, "signal">) => Promise<void>;
wait(delay: number, options?: { signal?: AbortSignal }): Promise<void>;
/**
* An experimental API defined by the [Scheduling APIs](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking) draft specification
* An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification
* being developed as a standard Web Platform API.
* Calling `timersPromises.scheduler.yield()` is equivalent to calling `timersPromises.setImmediate()` with no arguments.
* @since v16.14.0
*
* Calling `timersPromises.scheduler.yield()` is equivalent to calling
* `timersPromises.setImmediate()` with no arguments.
* @since v17.3.0, v16.14.0
* @experimental
*/
yield: () => Promise<void>;
yield(): Promise<void>;
}
const scheduler: Scheduler;
}

101
node_modules/@types/node/tls.d.ts generated vendored
View File

@@ -4,9 +4,9 @@
* The module can be accessed using:
*
* ```js
* const tls = require('node:tls');
* import tls from 'node:tls';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tls.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js)
*/
declare module "tls" {
import { X509Certificate } from "node:crypto";
@@ -398,6 +398,14 @@ declare module "tls" {
},
callback: (err: Error | null) => void,
): undefined | boolean;
/**
* The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket.
* This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`.
* @since v22.5.0, v20.17.0
* @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`,
* or a TLS context object created with {@link createSecureContext()} itself.
*/
setKeyCert(context: SecureContextOptions | SecureContext): void;
/**
* The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size.
* Returns `true` if setting the limit succeeded; `false` otherwise.
@@ -639,7 +647,7 @@ declare module "tls" {
* @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created
* with {@link createSecureContext} itself.
*/
addContext(hostname: string, context: SecureContextOptions): void;
addContext(hostname: string, context: SecureContextOptions | SecureContext): void;
/**
* Returns the session ticket keys.
*
@@ -789,13 +797,6 @@ declare module "tls" {
prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
}
/**
* @deprecated since v0.11.3 Use `tls.TLSSocket` instead.
*/
interface SecurePair {
encrypted: TLSSocket;
cleartext: TLSSocket;
}
type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";
interface SecureContextOptions {
/**
@@ -809,6 +810,12 @@ declare module "tls" {
* This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error.
*/
ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined;
/**
* Treat intermediate (non-self-signed)
* certificates in the trust CA certificate list as trusted.
* @since v22.9.0, v20.18.0
*/
allowPartialTrustChain?: boolean | undefined;
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
@@ -1003,8 +1010,8 @@ declare module "tls" {
* The following illustrates a simple echo server:
*
* ```js
* const tls = require('node:tls');
* const fs = require('node:fs');
* import tls from 'node:tls';
* import fs from 'node:fs';
*
* const options = {
* key: fs.readFileSync('server-key.pem'),
@@ -1049,8 +1056,8 @@ declare module "tls" {
*
* ```js
* // Assumes an echo server that is listening on port 8000.
* const tls = require('node:tls');
* const fs = require('node:fs');
* import tls from 'node:tls';
* import fs from 'node:fs';
*
* const options = {
* // Necessary only if the server requires client certificate authentication.
@@ -1088,45 +1095,6 @@ declare module "tls" {
secureConnectListener?: () => void,
): TLSSocket;
function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
/**
* Creates a new secure pair object with two streams, one of which reads and writes
* the encrypted data and the other of which reads and writes the cleartext data.
* Generally, the encrypted stream is piped to/from an incoming encrypted data
* stream and the cleartext one is used as a replacement for the initial encrypted
* stream.
*
* `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties.
*
* Using `cleartext` has the same API as {@link TLSSocket}.
*
* The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code:
*
* ```js
* pair = tls.createSecurePair(// ... );
* pair.encrypted.pipe(socket);
* socket.pipe(pair.encrypted);
* ```
*
* can be replaced by:
*
* ```js
* secureSocket = tls.TLSSocket(socket, options);
* ```
*
* where `secureSocket` has the same API as `pair.cleartext`.
* @since v0.3.2
* @deprecated Since v0.11.3 - Use {@link TLSSocket} instead.
* @param context A secure context object as returned by `tls.createSecureContext()`
* @param isServer `true` to specify that this TLS connection should be opened as a server.
* @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.
* @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.
*/
function createSecurePair(
context?: SecureContext,
isServer?: boolean,
requestCert?: boolean,
rejectUnauthorized?: boolean,
): SecurePair;
/**
* `{@link createServer}` sets the default value of the `honorCipherOrder` option
* to `true`, other APIs that create secure contexts leave it unset.
@@ -1152,13 +1120,38 @@ 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
* the `ciphers` option of `{@link createSecureContext}`.
*
* Not all supported ciphers are enabled by default. See
* [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v22.x/api/tls.html#modifying-the-default-tls-cipher-suite).
* [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite).
*
* Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for
* TLSv1.2 and below.

View File

@@ -9,8 +9,8 @@
* The available categories are:
*
* * `node`: An empty placeholder.
* * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) trace data.
* The [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property.
* * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) trace data.
* The [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property.
* * `node.bootstrap`: Enables capture of Node.js bootstrap milestones.
* * `node.console`: Enables capture of `console.time()` and `console.count()` output.
* * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.
@@ -22,7 +22,7 @@
* * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods.
* * `node.fs.async`: Enables capture of trace data for file system async methods.
* * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods.
* * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v22.x/api/perf_hooks.html) measurements.
* * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v24.x/api/perf_hooks.html) measurements.
* * `node.perf.usertiming`: Enables capture of only Performance API User Timing
* measures and marks.
* * `node.perf.timerify`: Enables capture of only Performance API timerify
@@ -30,7 +30,7 @@
* * `node.promises.rejections`: Enables capture of trace data tracking the number
* of unhandled Promise rejections and handled-after-rejections.
* * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods.
* * `v8`: The [V8](https://nodejs.org/docs/latest-v22.x/api/v8.html) events are GC, compiling, and execution related.
* * `v8`: The [V8](https://nodejs.org/docs/latest-v24.x/api/v8.html) events are GC, compiling, and execution related.
* * `node.http`: Enables capture of trace data for http request / response.
*
* By default the `node`, `node.async_hooks`, and `v8` categories are enabled.
@@ -53,7 +53,7 @@
* Alternatively, trace events may be enabled using the `node:trace_events` module:
*
* ```js
* const trace_events = require('node:trace_events');
* import trace_events from 'node:trace_events';
* const tracing = trace_events.createTracing({ categories: ['node.perf'] });
* tracing.enable(); // Enable trace event capture for the 'node.perf' category
*
@@ -88,9 +88,9 @@
* However the trace-event timestamps are expressed in microseconds,
* unlike `process.hrtime()` which returns nanoseconds.
*
* The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#class-worker) threads.
* The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#class-worker) threads.
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/trace_events.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/trace_events.js)
*/
declare module "trace_events" {
/**
@@ -118,7 +118,7 @@ declare module "trace_events" {
* will be disabled.
*
* ```js
* const trace_events = require('node:trace_events');
* import trace_events from 'node:trace_events';
* const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
* const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
* t1.enable();
@@ -159,7 +159,7 @@ declare module "trace_events" {
* Creates and returns a `Tracing` object for the given set of `categories`.
*
* ```js
* const trace_events = require('node:trace_events');
* import trace_events from 'node:trace_events';
* const categories = ['node.perf', 'node.async_hooks'];
* const tracing = trace_events.createTracing({ categories });
* tracing.enable();
@@ -178,7 +178,7 @@ declare module "trace_events" {
* Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console.
*
* ```js
* const trace_events = require('node:trace_events');
* import trace_events from 'node:trace_events';
* const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
* const t2 = trace_events.createTracing({ categories: ['node.perf'] });
* const t3 = trace_events.createTracing({ categories: ['v8'] });

4
node_modules/@types/node/tty.d.ts generated vendored
View File

@@ -3,7 +3,7 @@
* directly. However, it can be accessed using:
*
* ```js
* const tty = require('node:tty');
* import tty from 'node:tty';
* ```
*
* When Node.js detects that it is being run with a text terminal ("TTY")
@@ -21,7 +21,7 @@
*
* In most cases, there should be little to no reason for an application to
* manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tty.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tty.js)
*/
declare module "tty" {
import * as net from "node:net";

101
node_modules/@types/node/url.d.ts generated vendored
View File

@@ -5,7 +5,7 @@
* ```js
* import url from 'node:url';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/url.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js)
*/
declare module "url" {
import { Blob as NodeBlob } from "node:buffer";
@@ -93,7 +93,7 @@ declare module "url" {
* The `url.format()` method returns a formatted URL string derived from `urlObject`.
*
* ```js
* const url = require('node:url');
* import url from 'node:url';
* url.format({
* protocol: 'https',
* hostname: 'example.com',
@@ -157,7 +157,7 @@ declare module "url" {
* The `url.format()` method returns a formatted URL string derived from `urlObject`.
*
* ```js
* const url = require('node:url');
* import url from 'node:url';
* url.format({
* protocol: 'https',
* hostname: 'example.com',
@@ -222,7 +222,7 @@ declare module "url" {
* manner similar to that of a web browser resolving an anchor tag.
*
* ```js
* const url = require('node:url');
* import url from 'node:url';
* url.resolve('/one/two/three', 'four'); // '/one/two/four'
* url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
* url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
@@ -400,10 +400,10 @@ declare module "url" {
* Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later.
*
* ```js
* const {
* import {
* Blob,
* resolveObjectURL,
* } = require('node:buffer');
* } from 'node:buffer';
*
* const blob = new Blob(['hello']);
* const id = URL.createObjectURL(blob);
@@ -420,14 +420,12 @@ declare module "url" {
* Threads, `Blob` objects registered within one Worker will not be available
* to other workers or the main thread.
* @since v16.7.0
* @experimental
*/
static createObjectURL(blob: NodeBlob): string;
/**
* Removes the stored `Blob` identified by the given ID. Attempting to revoke a
* ID that isn't registered will silently fail.
* @since v16.7.0
* @experimental
* @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`.
*/
static revokeObjectURL(id: string): void;
@@ -757,6 +755,57 @@ declare module "url" {
*/
toJSON(): string;
}
interface URLPatternComponentResult {
input: string;
groups: Record<string, string | undefined>;
}
interface URLPatternInit {
protocol?: string;
username?: string;
password?: string;
hostname?: string;
port?: string;
pathname?: string;
search?: string;
hash?: string;
baseURL?: string;
}
interface URLPatternOptions {
ignoreCase?: boolean;
}
interface URLPatternResult {
inputs: (string | URLPatternInit)[];
protocol: URLPatternComponentResult;
username: URLPatternComponentResult;
password: URLPatternComponentResult;
hostname: URLPatternComponentResult;
port: URLPatternComponentResult;
pathname: URLPatternComponentResult;
search: URLPatternComponentResult;
hash: URLPatternComponentResult;
}
/**
* @since v23.8.0
* @experimental
*/
class URLPattern {
constructor(input: string | URLPatternInit, baseURL: string, options?: URLPatternOptions);
constructor(input?: string | URLPatternInit, options?: URLPatternOptions);
exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null;
readonly hasRegExpGroups: boolean;
readonly hash: string;
readonly hostname: string;
readonly password: string;
readonly pathname: string;
readonly port: string;
readonly protocol: string;
readonly search: string;
test(input?: string | URLPatternInit, baseURL?: string): boolean;
readonly username: string;
}
interface URLSearchParamsIterator<T> extends NodeJS.Iterator<T, NodeJS.BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): URLSearchParamsIterator<T>;
}
/**
* The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the
* four following constructors.
@@ -827,7 +876,7 @@ declare module "url" {
*
* Alias for `urlSearchParams[@@iterator]()`.
*/
entries(): IterableIterator<[string, string]>;
entries(): URLSearchParamsIterator<[string, string]>;
/**
* Iterates over each name-value pair in the query and invokes the given function.
*
@@ -881,7 +930,7 @@ declare module "url" {
* // foo
* ```
*/
keys(): IterableIterator<string>;
keys(): URLSearchParamsIterator<string>;
/**
* Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`,
* set the first such pair's value to `value` and remove all others. If not,
@@ -931,37 +980,33 @@ declare module "url" {
/**
* Returns an ES6 `Iterator` over the values of each name-value pair.
*/
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[string, string]>;
values(): URLSearchParamsIterator<string>;
[Symbol.iterator](): URLSearchParamsIterator<[string, string]>;
}
import { URL as _URL, URLSearchParams as _URLSearchParams } from "url";
import {
URL as _URL,
URLPattern as _URLPattern,
URLPatternInit as _URLPatternInit,
URLPatternResult as _URLPatternResult,
URLSearchParams as _URLSearchParams,
} from "url";
global {
interface URLSearchParams extends _URLSearchParams {}
interface URL extends _URL {}
interface Global {
URL: typeof _URL;
URLSearchParams: typeof _URLSearchParams;
}
/**
* `URL` class is a global reference for `require('url').URL`
* https://nodejs.org/api/url.html#the-whatwg-url-api
* @since v10.0.0
*/
var URL: typeof globalThis extends {
onmessage: any;
URL: infer T;
} ? T
: typeof _URL;
/**
* `URLSearchParams` class is a global reference for `require('url').URLSearchParams`
* https://nodejs.org/api/url.html#class-urlsearchparams
* @since v10.0.0
*/
interface URLSearchParams extends _URLSearchParams {}
var URLSearchParams: typeof globalThis extends {
onmessage: any;
URLSearchParams: infer T;
} ? T
: typeof _URLSearchParams;
interface URLPatternInit extends _URLPatternInit {}
interface URLPatternResult extends _URLPatternResult {}
interface URLPattern extends _URLPattern {}
var URLPattern: typeof _URLPattern;
}
}
declare module "node:url" {

822
node_modules/@types/node/util.d.ts generated vendored

File diff suppressed because it is too large Load Diff

201
node_modules/@types/node/v8.d.ts generated vendored
View File

@@ -2,9 +2,9 @@
* The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using:
*
* ```js
* const v8 = require('node:v8');
* import v8 from 'node:v8';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/v8.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js)
*/
declare module "v8" {
import { Readable } from "node:stream";
@@ -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
@@ -176,7 +257,7 @@ declare module "v8" {
*
* ```js
* // Print GC events to stdout for one minute.
* const v8 = require('node:v8');
* import v8 from 'node:v8';
* v8.setFlagsFromString('--trace_gc');
* setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
* ```
@@ -243,7 +324,7 @@ declare module "v8" {
*
* ```js
* // Print heap snapshot to the console
* const v8 = require('node:v8');
* import v8 from 'node:v8';
* const stream = v8.getHeapSnapshot();
* stream.pipe(process.stdout);
* ```
@@ -268,12 +349,12 @@ declare module "v8" {
* for a duration depending on the heap size.
*
* ```js
* const { writeHeapSnapshot } = require('node:v8');
* const {
* import { writeHeapSnapshot } from 'node:v8';
* import {
* Worker,
* isMainThread,
* parentPort,
* } = require('node:worker_threads');
* } from 'node:worker_threads';
*
* if (isMainThread) {
* const worker = new Worker(__filename);
@@ -319,6 +400,39 @@ declare module "v8" {
* @since v12.8.0
*/
function getHeapCodeStatistics(): HeapCodeStatistics;
/**
* V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string.
* If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true;
* otherwise, it returns false.
*
* If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`.
* Sometimes a `Latin-1` string may also be represented as `UTF16`.
*
* ```js
* const { isStringOneByteRepresentation } = require('node:v8');
*
* const Encoding = {
* latin1: 1,
* utf16le: 2,
* };
* const buffer = Buffer.alloc(100);
* function writeString(input) {
* if (isStringOneByteRepresentation(input)) {
* buffer.writeUint8(Encoding.latin1);
* buffer.writeUint32LE(input.length, 1);
* buffer.write(input, 5, 'latin1');
* } else {
* buffer.writeUint8(Encoding.utf16le);
* buffer.writeUint32LE(input.length * 2, 1);
* buffer.write(input, 5, 'utf16le');
* }
* }
* writeString('hello');
* writeString('你好');
* ```
* @since v23.10.0, v22.15.0
*/
function isStringOneByteRepresentation(content: string): boolean;
/**
* @since v8.0.0
*/
@@ -445,7 +559,7 @@ declare module "v8" {
* @since v8.0.0
* @param buffer A buffer returned by {@link serialize}.
*/
function deserialize(buffer: NodeJS.TypedArray): any;
function deserialize(buffer: NodeJS.ArrayBufferView): any;
/**
* The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple
* times during the lifetime of the process. Each time the execution counter will
@@ -466,8 +580,7 @@ declare module "v8" {
function stopCoverage(): void;
/**
* The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once.
* `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information.
* @experimental
* `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information.
* @since v18.10.0, v16.18.0
*/
function setHeapSnapshotNearHeapLimit(limit: number): void;
@@ -550,7 +663,7 @@ declare module "v8" {
* Here's an example.
*
* ```js
* const { GCProfiler } = require('v8');
* import { GCProfiler } from 'node:v8';
* const profiler = new GCProfiler();
* profiler.start();
* setTimeout(() => {
@@ -693,33 +806,6 @@ declare module "v8" {
*/
const promiseHooks: PromiseHooks;
type StartupSnapshotCallbackFn = (args: any) => any;
interface StartupSnapshot {
/**
* Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit.
* This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization.
* @since v18.6.0, v16.17.0
*/
addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
/**
* Add a callback that will be called when the Node.js instance is deserialized from a snapshot.
* The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or
* to re-acquire resources that the application needs when the application is restarted from the snapshot.
* @since v18.6.0, v16.17.0
*/
addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
/**
* This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script.
* If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized
* data (if provided), otherwise an entry point script still needs to be provided to the deserialized application.
* @since v18.6.0, v16.17.0
*/
setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void;
/**
* Returns true if the Node.js instance is run to build a snapshot.
* @since v18.6.0, v16.17.0
*/
isBuildingSnapshot(): boolean;
}
/**
* The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots.
*
@@ -736,12 +822,12 @@ declare module "v8" {
* ```js
* 'use strict';
*
* const fs = require('node:fs');
* const zlib = require('node:zlib');
* const path = require('node:path');
* const assert = require('node:assert');
* import fs from 'node:fs';
* import zlib from 'node:zlib';
* import path from 'node:path';
* import assert from 'node:assert';
*
* const v8 = require('node:v8');
* import v8 from 'node:v8';
*
* class BookShelf {
* storage = new Map();
@@ -798,10 +884,35 @@ declare module "v8" {
*
* Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot.
*
* @experimental
* @since v18.6.0, v16.17.0
*/
const startupSnapshot: StartupSnapshot;
namespace startupSnapshot {
/**
* Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit.
* This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization.
* @since v18.6.0, v16.17.0
*/
function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
/**
* Add a callback that will be called when the Node.js instance is deserialized from a snapshot.
* The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or
* to re-acquire resources that the application needs when the application is restarted from the snapshot.
* @since v18.6.0, v16.17.0
*/
function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
/**
* This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script.
* If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized
* data (if provided), otherwise an entry point script still needs to be provided to the deserialized application.
* @since v18.6.0, v16.17.0
*/
function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void;
/**
* Returns true if the Node.js instance is run to build a snapshot.
* @since v18.6.0, v16.17.0
*/
function isBuildingSnapshot(): boolean;
}
}
declare module "node:v8" {
export * from "v8";

206
node_modules/@types/node/vm.d.ts generated vendored
View File

@@ -17,7 +17,7 @@
* code are reflected in the context object.
*
* ```js
* const vm = require('node:vm');
* import vm from 'node:vm';
*
* const x = 1;
*
@@ -34,7 +34,7 @@
*
* console.log(x); // 1; y is not defined.
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/vm.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js)
*/
declare module "vm" {
import { ImportAttributes } from "node:module";
@@ -56,9 +56,15 @@ declare module "vm" {
*/
columnOffset?: number | undefined;
}
type DynamicModuleLoader<T> = (
specifier: string,
referrer: T,
importAttributes: ImportAttributes,
phase: "source" | "evaluation",
) => Module | Promise<Module>;
interface ScriptOptions extends BaseOptions {
/**
* V8's code cache data for the supplied source.
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: Buffer | NodeJS.ArrayBufferView | undefined;
/** @deprecated in favor of `script.createCachedData()` */
@@ -66,10 +72,11 @@ declare module "vm" {
/**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @experimental
*/
importModuleDynamically?:
| ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module)
| DynamicModuleLoader<Script>
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined;
}
@@ -110,18 +117,42 @@ declare module "vm" {
microtaskMode?: CreateContextOptions["microtaskMode"];
}
interface RunningCodeOptions extends RunningScriptOptions {
cachedData?: ScriptOptions["cachedData"];
importModuleDynamically?: ScriptOptions["importModuleDynamically"];
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
/**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @experimental
*/
importModuleDynamically?:
| DynamicModuleLoader<Script>
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined;
}
interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions {
cachedData?: ScriptOptions["cachedData"];
importModuleDynamically?: ScriptOptions["importModuleDynamically"];
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
/**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @experimental
*/
importModuleDynamically?:
| DynamicModuleLoader<Script>
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined;
}
interface CompileFunctionOptions extends BaseOptions {
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: Buffer | undefined;
cachedData?: ScriptOptions["cachedData"] | undefined;
/**
* Specifies whether to produce new cache data.
* @default false
@@ -135,6 +166,16 @@ declare module "vm" {
* An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling
*/
contextExtensions?: Object[] | undefined;
/**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @experimental
*/
importModuleDynamically?:
| DynamicModuleLoader<ReturnType<typeof compileFunction>>
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined;
}
interface CreateContextOptions {
/**
@@ -169,6 +210,16 @@ declare module "vm" {
* If set to `afterEvaluate`, microtasks will be run immediately after the script has run.
*/
microtaskMode?: "afterEvaluate" | undefined;
/**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @experimental
*/
importModuleDynamically?:
| DynamicModuleLoader<Context>
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined;
}
type MeasureMemoryMode = "summary" | "detailed";
interface MeasureMemoryOptions {
@@ -203,7 +254,7 @@ declare module "vm" {
* The globals are contained in the `context` object.
*
* ```js
* const vm = require('node:vm');
* import vm from 'node:vm';
*
* const context = {
* animal: 'cat',
@@ -230,9 +281,16 @@ declare module "vm" {
*/
runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any;
/**
* First contextifies the given `contextObject`, runs the compiled code contained
* by the `vm.Script` object within the created context, and returns the result.
* Running code does not have access to local scope.
* This method is a shortcut to `script.runInContext(vm.createContext(options), options)`.
* It does several things at once:
*
* 1. Creates a new context.
* 2. If `contextObject` is an object, contextifies it with the new context.
* If `contextObject` is undefined, creates a new object and contextifies it.
* If `contextObject` is `vm.constants.DONT_CONTEXTIFY`, don't contextify anything.
* 3. Runs the compiled code contained by the `vm.Script` object within the created context. The code
* does not have access to the scope in which this method is called.
* 4. Returns the result.
*
* The following example compiles code that sets a global variable, then executes
* the code multiple times in different contexts. The globals are set on and
@@ -250,12 +308,22 @@ declare module "vm" {
*
* console.log(contexts);
* // 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
* // global objects that can be frozen.
* const freezeScript = new vm.Script('Object.freeze(globalThis); globalThis;');
* const frozenContext = freezeScript.runInNewContext(vm.constants.DONT_CONTEXTIFY);
* ```
* @since v0.3.1
* @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created.
* @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified.
* If `undefined`, an empty contextified object will be created for backwards compatibility.
* @return the result of the very last statement executed in the script.
*/
runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any;
runInNewContext(
contextObject?: Context | typeof constants.DONT_CONTEXTIFY,
options?: RunningScriptInNewContextOptions,
): any;
/**
* Runs the compiled code contained by the `vm.Script` within the context of the
* current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object.
@@ -264,7 +332,7 @@ declare module "vm" {
* executes that code multiple times:
*
* ```js
* const vm = require('node:vm');
* import vm from 'node:vm';
*
* global.globalVar = 0;
*
@@ -347,13 +415,13 @@ declare module "vm" {
sourceMapURL?: string | undefined;
}
/**
* If given a `contextObject`, the `vm.createContext()` method will
* [prepare that object](https://nodejs.org/docs/latest-v22.x/api/vm.html#what-does-it-mean-to-contextify-an-object)
* and return a reference to it so that it can be used in `{@link runInContext}` or
* [`script.runInContext()`](https://nodejs.org/docs/latest-v22.x/api/vm.html#scriptrunincontextcontextifiedobject-options). Inside such
* scripts, the `contextObject` will be the global object, retaining all of its
* existing properties but also having the built-in objects and functions any
* standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global
* If the given `contextObject` is an object, the `vm.createContext()` method will
* [prepare that object](https://nodejs.org/docs/latest-v24.x/api/vm.html#what-does-it-mean-to-contextify-an-object)
* and return a reference to it so that it can be used in calls to {@link runInContext} or
* [`script.runInContext()`](https://nodejs.org/docs/latest-v24.x/api/vm.html#scriptrunincontextcontextifiedobject-options).
* Inside such scripts, the global object will be wrapped by the `contextObject`, retaining all of its
* existing properties but also having the built-in objects and functions any standard
* [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global
* variables will remain unchanged.
*
* ```js
@@ -374,7 +442,12 @@ declare module "vm" {
* ```
*
* If `contextObject` is omitted (or passed explicitly as `undefined`), a new,
* empty `contextified` object will be returned.
* empty contextified object will be returned.
*
* When the global object in the newly created context is contextified, it has some quirks
* compared to ordinary global objects. For example, it cannot be frozen. To create a context
* without the contextifying quirks, pass `vm.constants.DONT_CONTEXTIFY` as the `contextObject`
* argument. See the documentation of `vm.constants.DONT_CONTEXTIFY` for details.
*
* The `vm.createContext()` method is primarily useful for creating a single
* context that can be used to run multiple scripts. For instance, if emulating a
@@ -385,11 +458,17 @@ declare module "vm" {
* The provided `name` and `origin` of the context are made visible through the
* Inspector API.
* @since v0.3.1
* @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified.
* If `undefined`, an empty contextified object will be created for backwards compatibility.
* @return contextified object.
*/
function createContext(sandbox?: Context, options?: CreateContextOptions): Context;
function createContext(
contextObject?: Context | typeof constants.DONT_CONTEXTIFY,
options?: CreateContextOptions,
): Context;
/**
* Returns `true` if the given `object` object has been `contextified` using {@link createContext}.
* Returns `true` if the given `object` object has been contextified using {@link createContext},
* or if it's the global object of a context created using `vm.constants.DONT_CONTEXTIFY`.
* @since v0.11.7
*/
function isContext(sandbox: Context): boolean;
@@ -404,7 +483,7 @@ declare module "vm" {
* The following example compiles and executes different scripts using a single `contextified` object:
*
* ```js
* const vm = require('node:vm');
* import vm from 'node:vm';
*
* const contextObject = { globalVar: 1 };
* vm.createContext(contextObject);
@@ -422,13 +501,21 @@ declare module "vm" {
*/
function runInContext(code: string, contextifiedObject: Context, options?: RunningCodeOptions | string): any;
/**
* The `vm.runInNewContext()` first contextifies the given `contextObject` (or
* creates a new `contextObject` if passed as `undefined`), compiles the `code`,
* runs it within the created context, then returns the result. Running code
* does not have access to the local scope.
*
* This method is a shortcut to
* `(new vm.Script(code, options)).runInContext(vm.createContext(options), options)`.
* If `options` is a string, then it specifies the filename.
*
* It does several things at once:
*
* 1. Creates a new context.
* 2. If `contextObject` is an object, contextifies it with the new context.
* If `contextObject` is undefined, creates a new object and contextifies it.
* If `contextObject` is `vm.constants.DONT_CONTEXTIFY`, don't contextify anything.
* 3. Compiles the code as a`vm.Script`
* 4. Runs the compield code within the created context. The code does not have access to the scope in
* which this method is called.
* 5. Returns the result.
*
* The following example compiles and executes code that increments a global
* variable and sets a new one. These globals are contained in the `contextObject`.
*
@@ -443,15 +530,21 @@ declare module "vm" {
* vm.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);
* ```
* @since v0.3.1
* @param code The JavaScript code to compile and run.
* @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created.
* @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified.
* If `undefined`, an empty contextified object will be created for backwards compatibility.
* @return the result of the very last statement executed in the script.
*/
function runInNewContext(
code: string,
contextObject?: Context,
contextObject?: Context | typeof constants.DONT_CONTEXTIFY,
options?: RunningCodeInNewContextOptions | string,
): any;
/**
@@ -465,7 +558,7 @@ 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
* const vm = require('node:vm');
* import vm from 'node:vm';
* let localVar = 'initial value';
*
* const vmResult = vm.runInThisContext('localVar = "vm";');
@@ -487,16 +580,16 @@ declare module "vm" {
* 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 call `require('node:http')` on its own, or have a
* 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';
* const vm = require('node:vm');
* import vm from 'node:vm';
*
* const code = `
* ((require) => {
* const http = require('node:http');
* const http = require('node:http');
*
* http.createServer((request, response) => {
* response.writeHead(200, { 'Content-Type': 'text/plain' });
@@ -547,7 +640,7 @@ declare module "vm" {
* the memory occupied by each heap space in the current V8 instance.
*
* ```js
* const vm = require('node:vm');
* import vm from 'node:vm';
* // Measure the memory used by the main context.
* vm.measureMemory({ mode: 'summary' })
* // This is the same as vm.measureMemory()
@@ -806,6 +899,9 @@ declare module "vm" {
* @default 'vm:module(i)' where i is a context-specific ascending index.
*/
identifier?: string | undefined;
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
context?: Context | undefined;
lineOffset?: BaseOptions["lineOffset"] | undefined;
@@ -814,7 +910,13 @@ declare module "vm" {
* Called during evaluation of this module to initialize the `import.meta`.
*/
initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined;
importModuleDynamically?: ScriptOptions["importModuleDynamically"] | undefined;
/**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
* [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @experimental
*/
importModuleDynamically?: DynamicModuleLoader<SourceTextModule> | undefined;
}
/**
* This feature is only available with the `--experimental-vm-modules` command
@@ -853,7 +955,7 @@ declare module "vm" {
* module graphs.
*
* ```js
* const vm = require('node:vm');
* import vm from 'node:vm';
*
* const source = '{ "a": 1 }';
* const module = new vm.SyntheticModule(['default'], function() {
@@ -902,19 +1004,31 @@ declare module "vm" {
}
/**
* Returns an object containing commonly used constants for VM operations.
* @since v20.12.0
* @since v21.7.0, v20.12.0
*/
namespace constants {
/**
* Stability: 1.1 - Active development
*
* A constant that can be used as the `importModuleDynamically` option to `vm.Script`
* and `vm.compileFunction()` so that Node.js uses the default ESM loader from the main
* context to load the requested module.
*
* For detailed information, see [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* For detailed information, see [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
* @since v21.7.0, v20.12.0
*/
const USE_MAIN_CONTEXT_DEFAULT_LOADER: number;
/**
* This constant, when used as the `contextObject` argument in vm APIs, instructs Node.js to create
* a context without wrapping its global object with another object in a Node.js-specific manner.
* As a result, the `globalThis` value inside the new context would behave more closely to an ordinary
* one.
*
* When `vm.constants.DONT_CONTEXTIFY` is used as the `contextObject` argument to {@link createContext},
* the returned object is a proxy-like object to the global object in the newly created context with
* fewer Node.js-specific quirks. It is reference equal to the `globalThis` value in the new context,
* can be modified from outside the context, and can be used to access built-ins in the new context directly.
* @since v22.8.0
*/
const DONT_CONTEXTIFY: number;
}
}
declare module "node:vm" {

4
node_modules/@types/node/wasi.d.ts generated vendored
View File

@@ -9,7 +9,7 @@
*
* ```js
* import { readFile } from 'node:fs/promises';
* import { WASI } from 'wasi';
* import { WASI } from 'node:wasi';
* import { argv, env } from 'node:process';
*
* const wasi = new WASI({
@@ -67,7 +67,7 @@
* wat2wasm demo.wat
* ```
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/wasi.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/wasi.js)
*/
declare module "wasi" {
interface WASIOptions {

View File

@@ -3,7 +3,7 @@
* JavaScript in parallel. To access it:
*
* ```js
* const worker = require('node:worker_threads');
* import worker from 'node:worker_threads';
* ```
*
* Workers (threads) are useful for performing CPU-intensive JavaScript operations.
@@ -14,29 +14,32 @@
* so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer` instances.
*
* ```js
* const {
* Worker, isMainThread, parentPort, workerData,
* } = require('node:worker_threads');
* import {
* Worker,
* isMainThread,
* parentPort,
* workerData,
* } from 'node:worker_threads';
*
* if (isMainThread) {
* module.exports = function parseJSAsync(script) {
* return new Promise((resolve, reject) => {
* const worker = new Worker(__filename, {
* workerData: script,
* });
* worker.on('message', resolve);
* worker.on('error', reject);
* worker.on('exit', (code) => {
* if (code !== 0)
* reject(new Error(`Worker stopped with exit code ${code}`));
* });
* });
* };
* } else {
* const { parse } = require('some-js-parsing-library');
* if (!isMainThread) {
* const { parse } = await import('some-js-parsing-library');
* const script = workerData;
* parentPort.postMessage(parse(script));
* }
*
* export default function parseJSAsync(script) {
* return new Promise((resolve, reject) => {
* const worker = new Worker(new URL(import.meta.url), {
* workerData: script,
* });
* worker.on('message', resolve);
* worker.on('error', reject);
* worker.on('exit', (code) => {
* if (code !== 0)
* reject(new Error(`Worker stopped with exit code ${code}`));
* });
* });
* };
* ```
*
* The above example spawns a Worker thread for each `parseJSAsync()` call. In
@@ -49,17 +52,18 @@
*
* Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options,
* specifically `argv` and `execArgv` options.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/worker_threads.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/worker_threads.js)
*/
declare module "worker_threads" {
import { Blob } from "node:buffer";
import { Context } from "node:vm";
import { EventEmitter } from "node:events";
import { EventLoopUtilityFunction } from "node:perf_hooks";
import { FileHandle } from "node:fs/promises";
import { Readable, Writable } from "node:stream";
import { ReadableStream, TransformStream, WritableStream } from "node:stream/web";
import { URL } from "node:url";
import { X509Certificate } from "node:crypto";
import { HeapInfo } from "node:v8";
const isInternalThread: boolean;
const isMainThread: boolean;
const parentPort: null | MessagePort;
const resourceLimits: ResourceLimits;
@@ -72,7 +76,7 @@ declare module "worker_threads" {
* The `MessageChannel` has no methods of its own. `new MessageChannel()` yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances.
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
* import { MessageChannel } from 'node:worker_threads';
*
* const { port1, port2 } = new MessageChannel();
* port1.on('message', (message) => console.log('received', message));
@@ -88,7 +92,17 @@ declare module "worker_threads" {
interface WorkerPerformance {
eventLoopUtilization: EventLoopUtilityFunction;
}
type TransferListItem = ArrayBuffer | MessagePort | FileHandle | X509Certificate | Blob;
type Transferable =
| ArrayBuffer
| MessagePort
| AbortSignal
| FileHandle
| ReadableStream
| WritableStream
| TransformStream;
/** @deprecated Use `import { Transferable } from "node:worker_threads"` instead. */
// TODO: remove in a future major @types/node version.
type TransferListItem = Transferable;
/**
* Instances of the `worker.MessagePort` class represent one end of an
* asynchronous, two-way communications channel. It can be used to transfer
@@ -121,7 +135,7 @@ declare module "worker_threads" {
* * `value` may not contain native (C++-backed) objects other than:
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
* import { MessageChannel } from 'node:worker_threads';
* const { port1, port2 } = new MessageChannel();
*
* port1.on('message', (message) => console.log(message));
@@ -143,7 +157,7 @@ declare module "worker_threads" {
* `value` may still contain `ArrayBuffer` instances that are not in `transferList`; in that case, the underlying memory is copied rather than moved.
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
* import { MessageChannel } from 'node:worker_threads';
* const { port1, port2 } = new MessageChannel();
*
* port1.on('message', (message) => console.log(message));
@@ -173,7 +187,12 @@ declare module "worker_threads" {
* behind this API, see the `serialization API of the node:v8 module`.
* @since v10.5.0
*/
postMessage(value: any, transferList?: readonly TransferListItem[]): void;
postMessage(value: any, transferList?: readonly Transferable[]): void;
/**
* If true, the `MessagePort` object will keep the Node.js event loop active.
* @since v18.1.0, v16.17.0
*/
hasRef(): boolean;
/**
* Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does _not_ let the program exit if it's the only active handle left (the default
* behavior). If the port is `ref()`ed, calling `ref()` again has no effect.
@@ -260,14 +279,14 @@ declare module "worker_threads" {
/**
* Additional data to send in the first worker message.
*/
transferList?: TransferListItem[] | undefined;
transferList?: Transferable[] | undefined;
/**
* @default true
*/
trackUnmanagedFds?: boolean | undefined;
/**
* An optional `name` to be appended to the worker title
* for debuggin/identification purposes, making the final title as
* for debugging/identification purposes, making the final title as
* `[worker ${id}] ${name}`.
*/
name?: string | undefined;
@@ -298,8 +317,8 @@ declare module "worker_threads" {
* Notable differences inside a Worker environment are:
*
* * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread.
* * The `require('node:worker_threads').isMainThread` property is set to `false`.
* * The `require('node:worker_threads').parentPort` message port is available.
* * The `import { isMainThread } from 'node:worker_threads'` variable is set to `false`.
* * The `import { parentPort } from 'node:worker_threads'` message port is available.
* * `process.exit()` does not stop the whole program, just the single thread,
* and `process.abort()` is not available.
* * `process.chdir()` and `process` methods that set group or user ids
@@ -334,10 +353,10 @@ declare module "worker_threads" {
* the thread barrier.
*
* ```js
* const assert = require('node:assert');
* const {
* import assert from 'node:assert';
* import {
* Worker, MessageChannel, MessagePort, isMainThread, parentPort,
* } = require('node:worker_threads');
* } from 'node:worker_threads';
* if (isMainThread) {
* const worker = new Worker(__filename);
* const subChannel = new MessageChannel();
@@ -377,7 +396,7 @@ declare module "worker_threads" {
readonly stderr: Readable;
/**
* An integer identifier for the referenced thread. Inside the worker thread,
* it is available as `require('node:worker_threads').threadId`.
* it is available as `import { threadId } from 'node:worker_threads'`.
* This value is unique for each `Worker` instance inside a single process.
* @since v10.5.0
*/
@@ -408,7 +427,7 @@ declare module "worker_threads" {
* See `port.postMessage()` for more details.
* @since v10.5.0
*/
postMessage(value: any, transferList?: readonly TransferListItem[]): void;
postMessage(value: any, transferList?: readonly Transferable[]): void;
/**
* Sends a value to another worker, identified by its thread ID.
* @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown.
@@ -424,7 +443,7 @@ declare module "worker_threads" {
postMessageToThread(
threadId: number,
value: any,
transferList: readonly TransferListItem[],
transferList: readonly Transferable[],
timeout?: number,
): Promise<void>;
/**
@@ -456,6 +475,13 @@ declare module "worker_threads" {
* @return A promise for a Readable Stream containing a V8 heap snapshot
*/
getHeapSnapshot(): Promise<Readable>;
/**
* This method returns a `Promise` that will resolve to an object identical to `v8.getHeapStatistics()`,
* or reject with an `ERR_WORKER_NOT_RUNNING` error if the worker is no longer running.
* This methods allows the statistics to be observed from outside the actual thread.
* @since v24.0.0
*/
getHeapStatistics(): Promise<HeapInfo>;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "exit", listener: (exitCode: number) => void): this;
addListener(event: "message", listener: (value: any) => void): this;
@@ -513,11 +539,11 @@ declare module "worker_threads" {
* ```js
* 'use strict';
*
* const {
* import {
* isMainThread,
* BroadcastChannel,
* Worker,
* } = require('node:worker_threads');
* } from 'node:worker_threads';
*
* const bc = new BroadcastChannel('hello');
*
@@ -571,7 +597,7 @@ declare module "worker_threads" {
* This operation cannot be undone.
*
* ```js
* const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
* import { MessageChannel, markAsUntransferable } from 'node:worker_threads';
*
* const pooledBuffer = new ArrayBuffer(8);
* const typedArray1 = new Uint8Array(pooledBuffer);
@@ -594,6 +620,39 @@ declare module "worker_threads" {
* @since v14.5.0, v12.19.0
*/
function markAsUntransferable(object: object): void;
/**
* Check if an object is marked as not transferable with
* {@link markAsUntransferable}.
* @since v21.0.0
*/
function isMarkedAsUntransferable(object: object): boolean;
/**
* Mark an object as not cloneable. If `object` is used as `message` in
* a `port.postMessage()` call, an error is thrown. This is a no-op if `object` is a
* primitive value.
*
* This has no effect on `ArrayBuffer`, or any `Buffer` like objects.
*
* This operation cannot be undone.
*
* ```js
* const { markAsUncloneable } = require('node:worker_threads');
*
* const anyObject = { foo: 'bar' };
* markAsUncloneable(anyObject);
* const { port1 } = new MessageChannel();
* try {
* // This will throw an error, because anyObject is not cloneable.
* port1.postMessage(anyObject)
* } catch (error) {
* // error.name === 'DataCloneError'
* }
* ```
*
* There is no equivalent to this API in browsers.
* @since v22.10.0
*/
function markAsUncloneable(object: object): void;
/**
* Transfer a `MessagePort` to a different `vm` Context. The original `port` object is rendered unusable, and the returned `MessagePort` instance
* takes its place.
@@ -616,7 +675,7 @@ declare module "worker_threads" {
* that contains the message payload, corresponding to the oldest message in the `MessagePort`'s queue.
*
* ```js
* const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
* import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
* const { port1, port2 } = new MessageChannel();
* port1.postMessage({ hello: 'world' });
*
@@ -642,12 +701,12 @@ declare module "worker_threads" {
* automatically.
*
* ```js
* const {
* import {
* Worker,
* isMainThread,
* setEnvironmentData,
* getEnvironmentData,
* } = require('node:worker_threads');
* } from 'node:worker_threads';
*
* if (isMainThread) {
* setEnvironmentData('Hello', 'World!');
@@ -667,7 +726,7 @@ declare module "worker_threads" {
* @param value Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value
* for the `key` will be deleted.
*/
function setEnvironmentData(key: Serializable, value: Serializable): void;
function setEnvironmentData(key: Serializable, value?: Serializable): void;
import {
BroadcastChannel as _BroadcastChannel,
@@ -675,8 +734,12 @@ declare module "worker_threads" {
MessagePort as _MessagePort,
} from "worker_threads";
global {
function structuredClone<T>(
value: T,
options?: { transfer?: Transferable[] },
): T;
/**
* `BroadcastChannel` class is a global reference for `require('worker_threads').BroadcastChannel`
* `BroadcastChannel` class is a global reference for `import { BroadcastChannel } from 'worker_threads'`
* https://nodejs.org/api/globals.html#broadcastchannel
* @since v18.0.0
*/
@@ -686,7 +749,7 @@ declare module "worker_threads" {
} ? T
: typeof _BroadcastChannel;
/**
* `MessageChannel` class is a global reference for `require('worker_threads').MessageChannel`
* `MessageChannel` class is a global reference for `import { MessageChannel } from 'worker_threads'`
* https://nodejs.org/api/globals.html#messagechannel
* @since v15.0.0
*/
@@ -696,7 +759,7 @@ declare module "worker_threads" {
} ? T
: typeof _MessageChannel;
/**
* `MessagePort` class is a global reference for `require('worker_threads').MessagePort`
* `MessagePort` class is a global reference for `import { MessagePort } from 'worker_threads'`
* https://nodejs.org/api/globals.html#messageport
* @since v15.0.0
*/

231
node_modules/@types/node/zlib.d.ts generated vendored
View File

@@ -5,23 +5,23 @@
* To access it:
*
* ```js
* const zlib = require('node:zlib');
* import zlib from 'node:zlib';
* ```
*
* Compression and decompression are built around the Node.js
* [Streams API](https://nodejs.org/docs/latest-v22.x/api/stream.html).
* [Streams API](https://nodejs.org/docs/latest-v24.x/api/stream.html).
*
* Compressing or decompressing a stream (such as a file) can be accomplished by
* piping the source stream through a `zlib` `Transform` stream into a destination
* stream:
*
* ```js
* const { createGzip } = require('node:zlib');
* const { pipeline } = require('node:stream');
* const {
* import { createGzip } from 'node:zlib';
* import { pipeline } from 'node:stream';
* import {
* createReadStream,
* createWriteStream,
* } = require('node:fs');
* } from 'node:fs';
*
* const gzip = createGzip();
* const source = createReadStream('input.txt');
@@ -36,7 +36,7 @@
*
* // Or, Promisified
*
* const { promisify } = require('node:util');
* import { promisify } from 'node:util';
* const pipe = promisify(pipeline);
*
* async function do_gzip(input, output) {
@@ -56,7 +56,7 @@
* It is also possible to compress or decompress data in a single step:
*
* ```js
* const { deflate, unzip } = require('node:zlib');
* import { deflate, unzip } from 'node:zlib';
*
* const input = '.................................';
* deflate(input, (err, buffer) => {
@@ -78,7 +78,7 @@
*
* // Or, Promisified
*
* const { promisify } = require('node:util');
* import { promisify } from 'node:util';
* const do_unzip = promisify(unzip);
*
* do_unzip(buffer)
@@ -89,7 +89,7 @@
* });
* ```
* @since v0.5.8
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/zlib.js)
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/zlib.js)
*/
declare module "zlib" {
import * as stream from "node:stream";
@@ -143,14 +143,37 @@ declare module "zlib" {
}
| undefined;
/**
* Limits output size when using [convenience methods](https://nodejs.org/docs/latest-v22.x/api/zlib.html#convenience-methods).
* Limits output size when using [convenience methods](https://nodejs.org/docs/latest-v24.x/api/zlib.html#convenience-methods).
* @default buffer.kMaxLength
*/
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-v24.x/api/zlib.html#zstd-constants).
*/
params?: { [key: number]: number | boolean } | undefined;
/**
* Limits output size when using
* [convenience methods](https://nodejs.org/docs/latest-v24.x/api/zlib.html#convenience-methods).
* @default buffer.kMaxLength
*/
maxOutputLength?: number | undefined;
}
interface Zlib {
/** @deprecated Use bytesWritten instead. */
readonly bytesRead: number;
readonly bytesWritten: number;
shell?: boolean | string | undefined;
close(callback?: () => void): void;
@@ -172,6 +195,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 +266,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 +395,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<Buffer>;
}
/**
* 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<Buffer>;
}
/**
* 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 +496,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 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 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_BUF_ERROR: 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_MEMLEVEL: number;
const Z_DEFAULT_MEMLEVEL: number;
const Z_MIN_LEVEL: number;
const Z_MAX_LEVEL: number;
const Z_DEFAULT_LEVEL: number;
const ZLIB_VERNUM: number;
const Z_MAX_MEMLEVEL: number;
const Z_MAX_WINDOWBITS: number;
const Z_MEM_ERROR: number;
const Z_MIN_CHUNK: number;
const Z_MIN_LEVEL: 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` */

2
node_modules/@types/ws/README.md generated vendored
View File

@@ -8,7 +8,7 @@ This package contains type definitions for ws (https://github.com/websockets/ws)
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws.
### Additional Details
* Last updated: Mon, 29 Jul 2024 08:38:03 GMT
* Last updated: Tue, 01 Apr 2025 02:59:53 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
# Credits

470
node_modules/@types/ws/index.d.mts generated vendored
View File

@@ -1,21 +1,451 @@
export {
AddressInfo,
CertMeta,
ClientOptions,
CloseEvent,
createWebSocketStream,
Data,
ErrorEvent,
Event,
EventListenerOptions,
MessageEvent,
PerMessageDeflateOptions,
RawData,
ServerOptions,
VerifyClientCallbackAsync,
VerifyClientCallbackSync,
WebSocket,
WebSocketServer,
} from "./index.js";
import WebSocket = require("./index.js");
/// <reference types="node" />
import { EventEmitter } from "events";
import {
Agent,
ClientRequest,
ClientRequestArgs,
IncomingMessage,
OutgoingHttpHeaders,
Server as HTTPServer,
} from "http";
import { Server as HTTPSServer } from "https";
import { createConnection } from "net";
import { Duplex, DuplexOptions } from "stream";
import { SecureContextOptions } from "tls";
import { URL } from "url";
import { ZlibOptions } from "zlib";
// can not get all overload of BufferConstructor['from'], need to copy all it's first arguments here
// https://github.com/microsoft/TypeScript/issues/32164
type BufferLike =
| string
| Buffer
| DataView
| number
| ArrayBufferView
| Uint8Array
| ArrayBuffer
| SharedArrayBuffer
| Blob
| readonly any[]
| readonly number[]
| { valueOf(): ArrayBuffer }
| { valueOf(): SharedArrayBuffer }
| { valueOf(): Uint8Array }
| { valueOf(): readonly number[] }
| { valueOf(): string }
| { [Symbol.toPrimitive](hint: string): string };
// WebSocket socket.
declare class WebSocket extends EventEmitter {
/** The connection is not yet open. */
static readonly CONNECTING: 0;
/** The connection is open and ready to communicate. */
static readonly OPEN: 1;
/** The connection is in the process of closing. */
static readonly CLOSING: 2;
/** The connection is closed. */
static readonly CLOSED: 3;
binaryType: "nodebuffer" | "arraybuffer" | "fragments";
readonly bufferedAmount: number;
readonly extensions: string;
/** Indicates whether the websocket is paused */
readonly isPaused: boolean;
readonly protocol: string;
/** The current state of the connection */
readonly readyState:
| typeof WebSocket.CONNECTING
| typeof WebSocket.OPEN
| typeof WebSocket.CLOSING
| typeof WebSocket.CLOSED;
readonly url: string;
/** The connection is not yet open. */
readonly CONNECTING: 0;
/** The connection is open and ready to communicate. */
readonly OPEN: 1;
/** The connection is in the process of closing. */
readonly CLOSING: 2;
/** The connection is closed. */
readonly CLOSED: 3;
onopen: ((event: WebSocket.Event) => void) | null;
onerror: ((event: WebSocket.ErrorEvent) => void) | null;
onclose: ((event: WebSocket.CloseEvent) => void) | null;
onmessage: ((event: WebSocket.MessageEvent) => void) | null;
constructor(address: null);
constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs);
constructor(
address: string | URL,
protocols?: string | string[],
options?: WebSocket.ClientOptions | ClientRequestArgs,
);
close(code?: number, data?: string | Buffer): void;
ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
// https://github.com/websockets/ws/issues/2076#issuecomment-1250354722
send(data: BufferLike, cb?: (err?: Error) => void): void;
send(
data: BufferLike,
options: {
mask?: boolean | undefined;
binary?: boolean | undefined;
compress?: boolean | undefined;
fin?: boolean | undefined;
},
cb?: (err?: Error) => void,
): void;
terminate(): void;
/**
* Pause the websocket causing it to stop emitting events. Some events can still be
* emitted after this is called, until all buffered data is consumed. This method
* is a noop if the ready state is `CONNECTING` or `CLOSED`.
*/
pause(): void;
/**
* Make a paused socket resume emitting events. This method is a noop if the ready
* state is `CONNECTING` or `CLOSED`.
*/
resume(): void;
// HTML5 WebSocket events
addEventListener<K extends keyof WebSocket.WebSocketEventMap>(
type: K,
listener:
| ((event: WebSocket.WebSocketEventMap[K]) => void)
| { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
options?: WebSocket.EventListenerOptions,
): void;
removeEventListener<K extends keyof WebSocket.WebSocketEventMap>(
type: K,
listener:
| ((event: WebSocket.WebSocketEventMap[K]) => void)
| { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
): void;
// Events
on(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
on(event: "error", listener: (this: WebSocket, error: Error) => void): this;
on(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
on(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
on(event: "open", listener: (this: WebSocket) => void): this;
on(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
on(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this;
on(
event: "unexpected-response",
listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
): this;
on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
once(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
once(event: "error", listener: (this: WebSocket, error: Error) => void): this;
once(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
once(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
once(event: "open", listener: (this: WebSocket) => void): this;
once(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
once(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this;
once(
event: "unexpected-response",
listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
): this;
once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
off(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
off(event: "error", listener: (this: WebSocket, error: Error) => void): this;
off(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
off(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
off(event: "open", listener: (this: WebSocket) => void): this;
off(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
off(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this;
off(
event: "unexpected-response",
listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
): this;
off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
addListener(event: "close", listener: (code: number, reason: Buffer) => void): this;
addListener(event: "error", listener: (error: Error) => void): this;
addListener(event: "upgrade", listener: (request: IncomingMessage) => void): this;
addListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
addListener(event: "open", listener: () => void): this;
addListener(event: "ping" | "pong", listener: (data: Buffer) => void): this;
addListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this;
addListener(
event: "unexpected-response",
listener: (request: ClientRequest, response: IncomingMessage) => void,
): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "close", listener: (code: number, reason: Buffer) => void): this;
removeListener(event: "error", listener: (error: Error) => void): this;
removeListener(event: "upgrade", listener: (request: IncomingMessage) => void): this;
removeListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
removeListener(event: "open", listener: () => void): this;
removeListener(event: "ping" | "pong", listener: (data: Buffer) => void): this;
removeListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this;
removeListener(
event: "unexpected-response",
listener: (request: ClientRequest, response: IncomingMessage) => void,
): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
declare namespace WebSocket {
/**
* Data represents the raw message payload received over the WebSocket.
*/
type RawData = Buffer | ArrayBuffer | Buffer[];
/**
* Data represents the message payload received over the WebSocket.
*/
type Data = string | Buffer | ArrayBuffer | Buffer[];
/**
* CertMeta represents the accepted types for certificate & key data.
*/
type CertMeta = string | string[] | Buffer | Buffer[];
/**
* VerifyClientCallbackSync is a synchronous callback used to inspect the
* incoming message. The return value (boolean) of the function determines
* whether or not to accept the handshake.
*/
type VerifyClientCallbackSync<Request extends IncomingMessage = IncomingMessage> = (info: {
origin: string;
secure: boolean;
req: Request;
}) => boolean;
/**
* VerifyClientCallbackAsync is an asynchronous callback used to inspect the
* incoming message. The return value (boolean) of the function determines
* whether or not to accept the handshake.
*/
type VerifyClientCallbackAsync<Request extends IncomingMessage = IncomingMessage> = (
info: { origin: string; secure: boolean; req: Request },
callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void,
) => void;
/**
* FinishRequestCallback is a callback for last minute customization of the
* headers. If finishRequest is set, then it has the responsibility to call
* request.end() once it is done setting request headers.
*/
type FinishRequestCallback = (request: ClientRequest, websocket: WebSocket) => void;
interface ClientOptions extends SecureContextOptions {
protocol?: string | undefined;
followRedirects?: boolean | undefined;
generateMask?(mask: Buffer): void;
handshakeTimeout?: number | undefined;
maxRedirects?: number | undefined;
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
localAddress?: string | undefined;
protocolVersion?: number | undefined;
headers?: { [key: string]: string } | undefined;
origin?: string | undefined;
agent?: Agent | undefined;
host?: string | undefined;
family?: number | undefined;
checkServerIdentity?(servername: string, cert: CertMeta): boolean;
rejectUnauthorized?: boolean | undefined;
allowSynchronousEvents?: boolean | undefined;
autoPong?: boolean | undefined;
maxPayload?: number | undefined;
skipUTF8Validation?: boolean | undefined;
createConnection?: typeof createConnection | undefined;
finishRequest?: FinishRequestCallback | undefined;
}
interface PerMessageDeflateOptions {
serverNoContextTakeover?: boolean | undefined;
clientNoContextTakeover?: boolean | undefined;
serverMaxWindowBits?: number | undefined;
clientMaxWindowBits?: number | undefined;
zlibDeflateOptions?:
| {
flush?: number | undefined;
finishFlush?: number | undefined;
chunkSize?: number | undefined;
windowBits?: number | undefined;
level?: number | undefined;
memLevel?: number | undefined;
strategy?: number | undefined;
dictionary?: Buffer | Buffer[] | DataView | undefined;
info?: boolean | undefined;
}
| undefined;
zlibInflateOptions?: ZlibOptions | undefined;
threshold?: number | undefined;
concurrencyLimit?: number | undefined;
}
interface Event {
type: string;
target: WebSocket;
}
interface ErrorEvent {
error: any;
message: string;
type: string;
target: WebSocket;
}
interface CloseEvent {
wasClean: boolean;
code: number;
reason: string;
type: string;
target: WebSocket;
}
interface MessageEvent {
data: Data;
type: string;
target: WebSocket;
}
interface WebSocketEventMap {
open: Event;
error: ErrorEvent;
close: CloseEvent;
message: MessageEvent;
}
interface EventListenerOptions {
once?: boolean | undefined;
}
interface ServerOptions<
U extends typeof WebSocket = typeof WebSocket,
V extends typeof IncomingMessage = typeof IncomingMessage,
> {
host?: string | undefined;
port?: number | undefined;
backlog?: number | undefined;
server?: HTTPServer<V> | HTTPSServer<V> | undefined;
verifyClient?:
| VerifyClientCallbackAsync<InstanceType<V>>
| VerifyClientCallbackSync<InstanceType<V>>
| undefined;
handleProtocols?: (protocols: Set<string>, request: InstanceType<V>) => string | false;
path?: string | undefined;
noServer?: boolean | undefined;
allowSynchronousEvents?: boolean | undefined;
autoPong?: boolean | undefined;
clientTracking?: boolean | undefined;
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
maxPayload?: number | undefined;
skipUTF8Validation?: boolean | undefined;
WebSocket?: U | undefined;
}
interface AddressInfo {
address: string;
family: string;
port: number;
}
}
export import AddressInfo = WebSocket.AddressInfo;
export import CertMeta = WebSocket.CertMeta;
export import ClientOptions = WebSocket.ClientOptions;
export import CloseEvent = WebSocket.CloseEvent;
export import Data = WebSocket.Data;
export import ErrorEvent = WebSocket.ErrorEvent;
export import Event = WebSocket.Event;
export import EventListenerOptions = WebSocket.EventListenerOptions;
export import FinishRequestCallback = WebSocket.FinishRequestCallback;
export import MessageEvent = WebSocket.MessageEvent;
export import PerMessageDeflateOptions = WebSocket.PerMessageDeflateOptions;
export import RawData = WebSocket.RawData;
export import ServerOptions = WebSocket.ServerOptions;
export import VerifyClientCallbackAsync = WebSocket.VerifyClientCallbackAsync;
export import VerifyClientCallbackSync = WebSocket.VerifyClientCallbackSync;
// WebSocket Server
declare class Server<
T extends typeof WebSocket = typeof WebSocket,
U extends typeof IncomingMessage = typeof IncomingMessage,
> extends EventEmitter {
options: WebSocket.ServerOptions<T, U>;
path: string;
clients: Set<InstanceType<T>>;
constructor(options?: WebSocket.ServerOptions<T, U>, callback?: () => void);
address(): WebSocket.AddressInfo | string | null;
close(cb?: (err?: Error) => void): void;
handleUpgrade(
request: InstanceType<U>,
socket: Duplex,
upgradeHead: Buffer,
callback: (client: InstanceType<T>, request: InstanceType<U>) => void,
): void;
shouldHandle(request: InstanceType<U>): boolean | Promise<boolean>;
// Events
on(event: "connection", cb: (this: Server<T>, websocket: InstanceType<T>, request: InstanceType<U>) => void): this;
on(event: "error", cb: (this: Server<T>, error: Error) => void): this;
on(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
on(event: "close" | "listening", cb: (this: Server<T>) => void): this;
on(
event: "wsClientError",
cb: (this: Server<T>, error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
on(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;
once(
event: "connection",
cb: (this: Server<T>, websocket: InstanceType<T>, request: InstanceType<U>) => void,
): this;
once(event: "error", cb: (this: Server<T>, error: Error) => void): this;
once(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
once(event: "close" | "listening", cb: (this: Server<T>) => void): this;
once(
event: "wsClientError",
cb: (this: Server<T>, error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
once(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;
off(event: "connection", cb: (this: Server<T>, websocket: InstanceType<T>, request: InstanceType<U>) => void): this;
off(event: "error", cb: (this: Server<T>, error: Error) => void): this;
off(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
off(event: "close" | "listening", cb: (this: Server<T>) => void): this;
off(
event: "wsClientError",
cb: (this: Server<T>, error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
off(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;
addListener(event: "connection", cb: (websocket: InstanceType<T>, request: InstanceType<U>) => void): this;
addListener(event: "error", cb: (error: Error) => void): this;
addListener(event: "headers", cb: (headers: string[], request: InstanceType<U>) => void): this;
addListener(event: "close" | "listening", cb: () => void): this;
addListener(event: "wsClientError", cb: (error: Error, socket: Duplex, request: InstanceType<U>) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "connection", cb: (websocket: InstanceType<T>, request: InstanceType<U>) => void): this;
removeListener(event: "error", cb: (error: Error) => void): this;
removeListener(event: "headers", cb: (headers: string[], request: InstanceType<U>) => void): this;
removeListener(event: "close" | "listening", cb: () => void): this;
removeListener(event: "wsClientError", cb: (error: Error, socket: Duplex, request: InstanceType<U>) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export { type Server };
export const WebSocketServer: typeof Server;
export interface WebSocketServer extends Server {} // eslint-disable-line @typescript-eslint/no-empty-interface
// WebSocket stream
export function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex;
export default WebSocket;
export { WebSocket };

70
node_modules/@types/ws/index.d.ts generated vendored
View File

@@ -10,6 +10,7 @@ import {
Server as HTTPServer,
} from "http";
import { Server as HTTPSServer } from "https";
import { createConnection } from "net";
import { Duplex, DuplexOptions } from "stream";
import { SecureContextOptions } from "tls";
import { URL } from "url";
@@ -26,6 +27,7 @@ type BufferLike =
| Uint8Array
| ArrayBuffer
| SharedArrayBuffer
| Blob
| readonly any[]
| readonly number[]
| { valueOf(): ArrayBuffer }
@@ -114,21 +116,26 @@ declare class WebSocket extends EventEmitter {
// HTML5 WebSocket events
addEventListener<K extends keyof WebSocket.WebSocketEventMap>(
type: K,
listener: (event: WebSocket.WebSocketEventMap[K]) => void,
listener:
| ((event: WebSocket.WebSocketEventMap[K]) => void)
| { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
options?: WebSocket.EventListenerOptions,
): void;
removeEventListener<K extends keyof WebSocket.WebSocketEventMap>(
type: K,
listener: (event: WebSocket.WebSocketEventMap[K]) => void,
listener:
| ((event: WebSocket.WebSocketEventMap[K]) => void)
| { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
): void;
// Events
on(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
on(event: "error", listener: (this: WebSocket, err: Error) => void): this;
on(event: "error", listener: (this: WebSocket, error: Error) => void): this;
on(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
on(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
on(event: "open", listener: (this: WebSocket) => void): this;
on(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
on(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this;
on(
event: "unexpected-response",
listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
@@ -136,11 +143,12 @@ declare class WebSocket extends EventEmitter {
on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
once(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
once(event: "error", listener: (this: WebSocket, err: Error) => void): this;
once(event: "error", listener: (this: WebSocket, error: Error) => void): this;
once(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
once(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
once(event: "open", listener: (this: WebSocket) => void): this;
once(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
once(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this;
once(
event: "unexpected-response",
listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
@@ -148,11 +156,12 @@ declare class WebSocket extends EventEmitter {
once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
off(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
off(event: "error", listener: (this: WebSocket, err: Error) => void): this;
off(event: "error", listener: (this: WebSocket, error: Error) => void): this;
off(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this;
off(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
off(event: "open", listener: (this: WebSocket) => void): this;
off(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this;
off(event: "redirect", listener: (this: WebSocket, url: string, request: ClientRequest) => void): this;
off(
event: "unexpected-response",
listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
@@ -160,11 +169,12 @@ declare class WebSocket extends EventEmitter {
off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
addListener(event: "close", listener: (code: number, reason: Buffer) => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "error", listener: (error: Error) => void): this;
addListener(event: "upgrade", listener: (request: IncomingMessage) => void): this;
addListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
addListener(event: "open", listener: () => void): this;
addListener(event: "ping" | "pong", listener: (data: Buffer) => void): this;
addListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this;
addListener(
event: "unexpected-response",
listener: (request: ClientRequest, response: IncomingMessage) => void,
@@ -172,11 +182,12 @@ declare class WebSocket extends EventEmitter {
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "close", listener: (code: number, reason: Buffer) => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: "error", listener: (error: Error) => void): this;
removeListener(event: "upgrade", listener: (request: IncomingMessage) => void): this;
removeListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
removeListener(event: "open", listener: () => void): this;
removeListener(event: "ping" | "pong", listener: (data: Buffer) => void): this;
removeListener(event: "redirect", listener: (url: string, request: ClientRequest) => void): this;
removeListener(
event: "unexpected-response",
listener: (request: ClientRequest, response: IncomingMessage) => void,
@@ -224,6 +235,13 @@ declare namespace WebSocket {
callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void,
) => void;
/**
* FinishRequestCallback is a callback for last minute customization of the
* headers. If finishRequest is set, then it has the responsibility to call
* request.end() once it is done setting request headers.
*/
type FinishRequestCallback = (request: ClientRequest, websocket: WebSocket) => void;
interface ClientOptions extends SecureContextOptions {
protocol?: string | undefined;
followRedirects?: boolean | undefined;
@@ -240,8 +258,12 @@ declare namespace WebSocket {
family?: number | undefined;
checkServerIdentity?(servername: string, cert: CertMeta): boolean;
rejectUnauthorized?: boolean | undefined;
allowSynchronousEvents?: boolean | undefined;
autoPong?: boolean | undefined;
maxPayload?: number | undefined;
skipUTF8Validation?: boolean | undefined;
createConnection?: typeof createConnection | undefined;
finishRequest?: FinishRequestCallback | undefined;
}
interface PerMessageDeflateOptions {
@@ -317,6 +339,8 @@ declare namespace WebSocket {
handleProtocols?: (protocols: Set<string>, request: InstanceType<V>) => string | false;
path?: string | undefined;
noServer?: boolean | undefined;
allowSynchronousEvents?: boolean | undefined;
autoPong?: boolean | undefined;
clientTracking?: boolean | undefined;
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
maxPayload?: number | undefined;
@@ -352,19 +376,30 @@ declare namespace WebSocket {
shouldHandle(request: InstanceType<U>): boolean | Promise<boolean>;
// Events
on(event: "connection", cb: (this: Server<T>, socket: InstanceType<T>, request: InstanceType<U>) => void): this;
on(
event: "connection",
cb: (this: Server<T>, websocket: InstanceType<T>, request: InstanceType<U>) => void,
): this;
on(event: "error", cb: (this: Server<T>, error: Error) => void): this;
on(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
on(event: "close" | "listening", cb: (this: Server<T>) => void): this;
on(
event: "wsClientError",
cb: (this: Server<T>, error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
on(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;
once(
event: "connection",
cb: (this: Server<T>, socket: InstanceType<T>, request: InstanceType<U>) => void,
cb: (this: Server<T>, websocket: InstanceType<T>, request: InstanceType<U>) => void,
): this;
once(event: "error", cb: (this: Server<T>, error: Error) => void): this;
once(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
once(event: "close" | "listening", cb: (this: Server<T>) => void): this;
once(
event: "wsClientError",
cb: (this: Server<T>, error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
once(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;
off(
@@ -374,18 +409,27 @@ declare namespace WebSocket {
off(event: "error", cb: (this: Server<T>, error: Error) => void): this;
off(event: "headers", cb: (this: Server<T>, headers: string[], request: InstanceType<U>) => void): this;
off(event: "close" | "listening", cb: (this: Server<T>) => void): this;
off(
event: "wsClientError",
cb: (this: Server<T>, error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
off(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this;
addListener(event: "connection", cb: (client: InstanceType<T>, request: InstanceType<U>) => void): this;
addListener(event: "error", cb: (err: Error) => void): this;
addListener(event: "connection", cb: (websocket: InstanceType<T>, request: InstanceType<U>) => void): this;
addListener(event: "error", cb: (error: Error) => void): this;
addListener(event: "headers", cb: (headers: string[], request: InstanceType<U>) => void): this;
addListener(event: "close" | "listening", cb: () => void): this;
addListener(event: "wsClientError", cb: (error: Error, socket: Duplex, request: InstanceType<U>) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "connection", cb: (client: InstanceType<T>, request: InstanceType<U>) => void): this;
removeListener(event: "error", cb: (err: Error) => void): this;
removeListener(event: "connection", cb: (websocket: InstanceType<T>, request: InstanceType<U>) => void): this;
removeListener(event: "error", cb: (error: Error) => void): this;
removeListener(event: "headers", cb: (headers: string[], request: InstanceType<U>) => void): this;
removeListener(event: "close" | "listening", cb: () => void): this;
removeListener(
event: "wsClientError",
cb: (error: Error, socket: Duplex, request: InstanceType<U>) => void,
): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
}

View File

@@ -1,6 +1,6 @@
{
"name": "@types/ws",
"version": "8.5.12",
"version": "8.18.1",
"description": "TypeScript definitions for ws",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ws",
"license": "MIT",
@@ -66,6 +66,7 @@
"dependencies": {
"@types/node": "*"
},
"typesPublisherContentHash": "32ddd11d89328bee2bba51767ec4f352327efde9e14bd1107492d0c8676d2cf6",
"typeScriptVersion": "4.8"
"peerDependencies": {},
"typesPublisherContentHash": "043c83a4bb92503ab01243879ee715fb6db391090d10883c5a2eb72099d22724",
"typeScriptVersion": "5.1"
}