@types/node
Advanced tools
Comparing version 14.14.20 to 20.9.5
1022
node/assert.d.ts
@@ -1,33 +0,189 @@ | ||
declare module 'assert' { | ||
/** An alias of `assert.ok()`. */ | ||
function assert(value: any, message?: string | Error): asserts value; | ||
/** | ||
* The `node:assert` module provides a set of assertion functions for verifying | ||
* invariants. | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) | ||
*/ | ||
declare module "assert" { | ||
/** | ||
* An alias of {@link ok}. | ||
* @since v0.5.9 | ||
* @param value The input that is checked for being truthy. | ||
*/ | ||
function assert(value: unknown, message?: string | Error): asserts value; | ||
namespace assert { | ||
/** | ||
* Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. | ||
*/ | ||
class AssertionError extends Error { | ||
actual: any; | ||
expected: any; | ||
/** | ||
* Set to the `actual` argument for methods such as {@link assert.strictEqual()}. | ||
*/ | ||
actual: unknown; | ||
/** | ||
* Set to the `expected` argument for methods such as {@link assert.strictEqual()}. | ||
*/ | ||
expected: unknown; | ||
/** | ||
* Set to the passed in operator value. | ||
*/ | ||
operator: string; | ||
/** | ||
* Indicates if the message was auto-generated (`true`) or not. | ||
*/ | ||
generatedMessage: boolean; | ||
code: 'ERR_ASSERTION'; | ||
/** | ||
* Value is always `ERR_ASSERTION` to show that the error is an assertion error. | ||
*/ | ||
code: "ERR_ASSERTION"; | ||
constructor(options?: { | ||
/** If provided, the error message is set to this value. */ | ||
message?: string; | ||
message?: string | undefined; | ||
/** The `actual` property on the error instance. */ | ||
actual?: any; | ||
actual?: unknown | undefined; | ||
/** The `expected` property on the error instance. */ | ||
expected?: any; | ||
expected?: unknown | undefined; | ||
/** The `operator` property on the error instance. */ | ||
operator?: string; | ||
operator?: string | undefined; | ||
/** If provided, the generated stack trace omits frames before this function. */ | ||
// tslint:disable-next-line:ban-types | ||
stackStartFn?: Function; | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
stackStartFn?: Function | undefined; | ||
}); | ||
} | ||
/** | ||
* This feature is deprecated and will be removed in a future version. | ||
* Please consider using alternatives such as the `mock` helper function. | ||
* @since v14.2.0, v12.19.0 | ||
* @deprecated Deprecated | ||
*/ | ||
class CallTracker { | ||
/** | ||
* The wrapper function is expected to be called exactly `exact` times. If the | ||
* function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an | ||
* error. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* // Creates call tracker. | ||
* const tracker = new assert.CallTracker(); | ||
* | ||
* function func() {} | ||
* | ||
* // Returns a function that wraps func() that must be called exact times | ||
* // before tracker.verify(). | ||
* const callsfunc = tracker.calls(func); | ||
* ``` | ||
* @since v14.2.0, v12.19.0 | ||
* @param [fn='A no-op function'] | ||
* @param [exact=1] | ||
* @return that wraps `fn`. | ||
*/ | ||
calls(exact?: number): () => void; | ||
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func; | ||
/** | ||
* Example: | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* const tracker = new assert.CallTracker(); | ||
* | ||
* function func() {} | ||
* const callsfunc = tracker.calls(func); | ||
* callsfunc(1, 2, 3); | ||
* | ||
* assert.deepStrictEqual(tracker.getCalls(callsfunc), | ||
* [{ thisArg: undefined, arguments: [1, 2, 3] }]); | ||
* ``` | ||
* @since v18.8.0, v16.18.0 | ||
* @param fn | ||
* @return An Array with all the calls to a tracked function. | ||
*/ | ||
getCalls(fn: Function): CallTrackerCall[]; | ||
/** | ||
* The arrays contains information about the expected and actual number of calls of | ||
* the functions that have not been called the expected number of times. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* // Creates call tracker. | ||
* const tracker = new assert.CallTracker(); | ||
* | ||
* function func() {} | ||
* | ||
* // Returns a function that wraps func() that must be called exact times | ||
* // before tracker.verify(). | ||
* const callsfunc = tracker.calls(func, 2); | ||
* | ||
* // Returns an array containing information on callsfunc() | ||
* console.log(tracker.report()); | ||
* // [ | ||
* // { | ||
* // message: 'Expected the func function to be executed 2 time(s) but was | ||
* // executed 0 time(s).', | ||
* // actual: 0, | ||
* // expected: 2, | ||
* // operator: 'func', | ||
* // stack: stack trace | ||
* // } | ||
* // ] | ||
* ``` | ||
* @since v14.2.0, v12.19.0 | ||
* @return An Array of objects containing information about the wrapper functions returned by `calls`. | ||
*/ | ||
report(): CallTrackerReportInformation[]; | ||
/** | ||
* Reset calls of the call tracker. | ||
* If a tracked function is passed as an argument, the calls will be reset for it. | ||
* If no arguments are passed, all tracked functions will be reset. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* const tracker = new assert.CallTracker(); | ||
* | ||
* function func() {} | ||
* const callsfunc = tracker.calls(func); | ||
* | ||
* callsfunc(); | ||
* // Tracker was called once | ||
* assert.strictEqual(tracker.getCalls(callsfunc).length, 1); | ||
* | ||
* tracker.reset(callsfunc); | ||
* assert.strictEqual(tracker.getCalls(callsfunc).length, 0); | ||
* ``` | ||
* @since v18.8.0, v16.18.0 | ||
* @param fn a tracked function to reset. | ||
*/ | ||
reset(fn?: Function): void; | ||
/** | ||
* Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that | ||
* have not been called the expected number of times. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* // Creates call tracker. | ||
* const tracker = new assert.CallTracker(); | ||
* | ||
* function func() {} | ||
* | ||
* // Returns a function that wraps func() that must be called exact times | ||
* // before tracker.verify(). | ||
* const callsfunc = tracker.calls(func, 2); | ||
* | ||
* callsfunc(); | ||
* | ||
* // Will throw an error since callsfunc() was only called once. | ||
* tracker.verify(); | ||
* ``` | ||
* @since v14.2.0, v12.19.0 | ||
*/ | ||
verify(): void; | ||
} | ||
interface CallTrackerCall { | ||
thisArg: object; | ||
arguments: unknown[]; | ||
} | ||
interface CallTrackerReportInformation { | ||
@@ -44,82 +200,798 @@ message: string; | ||
} | ||
type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error; | ||
type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; | ||
/** | ||
* Throws an `AssertionError` with the provided error message or a default | ||
* error message. If the `message` parameter is an instance of an `Error` then | ||
* it will be thrown instead of the `AssertionError`. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.fail(); | ||
* // AssertionError [ERR_ASSERTION]: Failed | ||
* | ||
* assert.fail('boom'); | ||
* // AssertionError [ERR_ASSERTION]: boom | ||
* | ||
* assert.fail(new TypeError('need array')); | ||
* // TypeError: need array | ||
* ``` | ||
* | ||
* Using `assert.fail()` with more than two arguments is possible but deprecated. | ||
* See below for further details. | ||
* @since v0.1.21 | ||
* @param [message='Failed'] | ||
*/ | ||
function fail(message?: string | Error): never; | ||
/** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ | ||
function fail( | ||
actual: any, | ||
expected: any, | ||
actual: unknown, | ||
expected: unknown, | ||
message?: string | Error, | ||
operator?: string, | ||
// tslint:disable-next-line:ban-types | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
stackStartFn?: Function, | ||
): never; | ||
function ok(value: any, message?: string | Error): asserts value; | ||
/** @deprecated since v9.9.0 - use strictEqual() instead. */ | ||
function equal(actual: any, expected: any, message?: string | Error): void; | ||
/** @deprecated since v9.9.0 - use notStrictEqual() instead. */ | ||
function notEqual(actual: any, expected: any, message?: string | Error): void; | ||
/** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ | ||
function deepEqual(actual: any, expected: any, message?: string | Error): void; | ||
/** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ | ||
function notDeepEqual(actual: any, expected: any, message?: string | Error): void; | ||
function strictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T; | ||
function notStrictEqual(actual: any, expected: any, message?: string | Error): void; | ||
function deepStrictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T; | ||
function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; | ||
function throws(block: () => any, message?: string | Error): void; | ||
function throws(block: () => any, error: AssertPredicate, message?: string | Error): void; | ||
function doesNotThrow(block: () => any, message?: string | Error): void; | ||
function doesNotThrow(block: () => any, error: AssertPredicate, message?: string | Error): void; | ||
function ifError(value: any): asserts value is null | undefined; | ||
function rejects(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>; | ||
/** | ||
* Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. | ||
* | ||
* If `value` is not truthy, an `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` then it will be thrown instead of the`AssertionError`. | ||
* If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. | ||
* | ||
* Be aware that in the `repl` the error message will be different to the one | ||
* thrown in a file! See below for further details. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.ok(true); | ||
* // OK | ||
* assert.ok(1); | ||
* // OK | ||
* | ||
* assert.ok(); | ||
* // AssertionError: No value argument passed to `assert.ok()` | ||
* | ||
* assert.ok(false, 'it\'s false'); | ||
* // AssertionError: it's false | ||
* | ||
* // In the repl: | ||
* assert.ok(typeof 123 === 'string'); | ||
* // AssertionError: false == true | ||
* | ||
* // In a file (e.g. test.js): | ||
* assert.ok(typeof 123 === 'string'); | ||
* // AssertionError: The expression evaluated to a falsy value: | ||
* // | ||
* // assert.ok(typeof 123 === 'string') | ||
* | ||
* assert.ok(false); | ||
* // AssertionError: The expression evaluated to a falsy value: | ||
* // | ||
* // assert.ok(false) | ||
* | ||
* assert.ok(0); | ||
* // AssertionError: The expression evaluated to a falsy value: | ||
* // | ||
* // assert.ok(0) | ||
* ``` | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* // Using `assert()` works the same: | ||
* assert(0); | ||
* // AssertionError: The expression evaluated to a falsy value: | ||
* // | ||
* // assert(0) | ||
* ``` | ||
* @since v0.1.21 | ||
*/ | ||
function ok(value: unknown, message?: string | Error): asserts value; | ||
/** | ||
* **Strict assertion mode** | ||
* | ||
* An alias of {@link strictEqual}. | ||
* | ||
* **Legacy assertion mode** | ||
* | ||
* > Stability: 3 - Legacy: Use {@link strictEqual} instead. | ||
* | ||
* Tests shallow, coercive equality between the `actual` and `expected` parameters | ||
* using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled | ||
* and treated as being identical if both sides are `NaN`. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* assert.equal(1, 1); | ||
* // OK, 1 == 1 | ||
* assert.equal(1, '1'); | ||
* // OK, 1 == '1' | ||
* assert.equal(NaN, NaN); | ||
* // OK | ||
* | ||
* assert.equal(1, 2); | ||
* // AssertionError: 1 == 2 | ||
* assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); | ||
* // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } | ||
* ``` | ||
* | ||
* If the values are not equal, an `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` then it will be thrown instead of the`AssertionError`. | ||
* @since v0.1.21 | ||
*/ | ||
function equal(actual: unknown, expected: unknown, message?: string | Error): void; | ||
/** | ||
* **Strict assertion mode** | ||
* | ||
* An alias of {@link notStrictEqual}. | ||
* | ||
* **Legacy assertion mode** | ||
* | ||
* > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. | ||
* | ||
* Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is | ||
* specially handled and treated as being identical if both sides are `NaN`. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* assert.notEqual(1, 2); | ||
* // OK | ||
* | ||
* assert.notEqual(1, 1); | ||
* // AssertionError: 1 != 1 | ||
* | ||
* assert.notEqual(1, '1'); | ||
* // AssertionError: 1 != '1' | ||
* ``` | ||
* | ||
* If the values are equal, an `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` then it will be thrown instead of the`AssertionError`. | ||
* @since v0.1.21 | ||
*/ | ||
function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; | ||
/** | ||
* **Strict assertion mode** | ||
* | ||
* An alias of {@link deepStrictEqual}. | ||
* | ||
* **Legacy assertion mode** | ||
* | ||
* > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. | ||
* | ||
* Tests for deep equality between the `actual` and `expected` parameters. Consider | ||
* using {@link deepStrictEqual} instead. {@link deepEqual} can have | ||
* surprising results. | ||
* | ||
* _Deep equality_ means that the enumerable "own" properties of child objects | ||
* are also recursively evaluated by the following rules. | ||
* @since v0.1.21 | ||
*/ | ||
function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; | ||
/** | ||
* **Strict assertion mode** | ||
* | ||
* An alias of {@link notDeepStrictEqual}. | ||
* | ||
* **Legacy assertion mode** | ||
* | ||
* > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. | ||
* | ||
* Tests for any deep inequality. Opposite of {@link deepEqual}. | ||
* | ||
* ```js | ||
* import assert from 'node:assert'; | ||
* | ||
* const obj1 = { | ||
* a: { | ||
* b: 1, | ||
* }, | ||
* }; | ||
* const obj2 = { | ||
* a: { | ||
* b: 2, | ||
* }, | ||
* }; | ||
* const obj3 = { | ||
* a: { | ||
* b: 1, | ||
* }, | ||
* }; | ||
* const obj4 = { __proto__: obj1 }; | ||
* | ||
* assert.notDeepEqual(obj1, obj1); | ||
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } | ||
* | ||
* assert.notDeepEqual(obj1, obj2); | ||
* // OK | ||
* | ||
* assert.notDeepEqual(obj1, obj3); | ||
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } | ||
* | ||
* assert.notDeepEqual(obj1, obj4); | ||
* // OK | ||
* ``` | ||
* | ||
* If the values are deeply equal, an `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` then it will be thrown | ||
* instead of the `AssertionError`. | ||
* @since v0.1.21 | ||
*/ | ||
function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; | ||
/** | ||
* Tests strict equality between the `actual` and `expected` parameters as | ||
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.strictEqual(1, 2); | ||
* // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: | ||
* // | ||
* // 1 !== 2 | ||
* | ||
* assert.strictEqual(1, 1); | ||
* // OK | ||
* | ||
* assert.strictEqual('Hello foobar', 'Hello World!'); | ||
* // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: | ||
* // + actual - expected | ||
* // | ||
* // + 'Hello foobar' | ||
* // - 'Hello World!' | ||
* // ^ | ||
* | ||
* const apples = 1; | ||
* const oranges = 2; | ||
* assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); | ||
* // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 | ||
* | ||
* assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); | ||
* // TypeError: Inputs are not identical | ||
* ``` | ||
* | ||
* If the values are not strictly equal, an `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` then it will be thrown | ||
* instead of the `AssertionError`. | ||
* @since v0.1.21 | ||
*/ | ||
function strictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T; | ||
/** | ||
* Tests strict inequality between the `actual` and `expected` parameters as | ||
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.notStrictEqual(1, 2); | ||
* // OK | ||
* | ||
* assert.notStrictEqual(1, 1); | ||
* // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: | ||
* // | ||
* // 1 | ||
* | ||
* assert.notStrictEqual(1, '1'); | ||
* // OK | ||
* ``` | ||
* | ||
* If the values are strictly equal, an `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` then it will be thrown | ||
* instead of the `AssertionError`. | ||
* @since v0.1.21 | ||
*/ | ||
function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; | ||
/** | ||
* Tests for 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. | ||
* @since v1.2.0 | ||
*/ | ||
function deepStrictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T; | ||
/** | ||
* Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); | ||
* // OK | ||
* ``` | ||
* | ||
* If the values are deeply and strictly equal, an `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` then it will be thrown | ||
* instead of the `AssertionError`. | ||
* @since v1.2.0 | ||
*/ | ||
function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; | ||
/** | ||
* Expects the function `fn` to throw an error. | ||
* | ||
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), | ||
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, | ||
* a validation object where each property will be tested for strict deep equality, | ||
* or an instance of error where each property will be tested for strict deep | ||
* equality including the non-enumerable `message` and `name` properties. When | ||
* using an object, it is also possible to use a regular expression, when | ||
* validating against a string property. See below for examples. | ||
* | ||
* If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation | ||
* fails. | ||
* | ||
* Custom validation object/error instance: | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* const err = new TypeError('Wrong value'); | ||
* err.code = 404; | ||
* err.foo = 'bar'; | ||
* err.info = { | ||
* nested: true, | ||
* baz: 'text', | ||
* }; | ||
* err.reg = /abc/i; | ||
* | ||
* assert.throws( | ||
* () => { | ||
* throw err; | ||
* }, | ||
* { | ||
* name: 'TypeError', | ||
* message: 'Wrong value', | ||
* info: { | ||
* nested: true, | ||
* baz: 'text', | ||
* }, | ||
* // Only properties on the validation object will be tested for. | ||
* // Using nested objects requires all properties to be present. Otherwise | ||
* // the validation is going to fail. | ||
* }, | ||
* ); | ||
* | ||
* // Using regular expressions to validate error properties: | ||
* assert.throws( | ||
* () => { | ||
* throw err; | ||
* }, | ||
* { | ||
* // The `name` and `message` properties are strings and using regular | ||
* // expressions on those will match against the string. If they fail, an | ||
* // error is thrown. | ||
* name: /^TypeError$/, | ||
* message: /Wrong/, | ||
* foo: 'bar', | ||
* info: { | ||
* nested: true, | ||
* // It is not possible to use regular expressions for nested properties! | ||
* baz: 'text', | ||
* }, | ||
* // The `reg` property contains a regular expression and only if the | ||
* // validation object contains an identical regular expression, it is going | ||
* // to pass. | ||
* reg: /abc/i, | ||
* }, | ||
* ); | ||
* | ||
* // Fails due to the different `message` and `name` properties: | ||
* assert.throws( | ||
* () => { | ||
* const otherErr = new Error('Not found'); | ||
* // Copy all enumerable properties from `err` to `otherErr`. | ||
* for (const [key, value] of Object.entries(err)) { | ||
* otherErr[key] = value; | ||
* } | ||
* throw otherErr; | ||
* }, | ||
* // The error's `message` and `name` properties will also be checked when using | ||
* // an error as validation object. | ||
* err, | ||
* ); | ||
* ``` | ||
* | ||
* Validate instanceof using constructor: | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.throws( | ||
* () => { | ||
* throw new Error('Wrong value'); | ||
* }, | ||
* Error, | ||
* ); | ||
* ``` | ||
* | ||
* Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): | ||
* | ||
* Using a regular expression runs `.toString` on the error object, and will | ||
* therefore also include the error name. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.throws( | ||
* () => { | ||
* throw new Error('Wrong value'); | ||
* }, | ||
* /^Error: Wrong value$/, | ||
* ); | ||
* ``` | ||
* | ||
* Custom error validation: | ||
* | ||
* The function must return `true` to indicate all internal validations passed. | ||
* It will otherwise fail with an `AssertionError`. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.throws( | ||
* () => { | ||
* throw new Error('Wrong value'); | ||
* }, | ||
* (err) => { | ||
* assert(err instanceof Error); | ||
* assert(/value/.test(err)); | ||
* // Avoid returning anything from validation functions besides `true`. | ||
* // Otherwise, it's not clear what part of the validation failed. Instead, | ||
* // throw an error about the specific validation that failed (as done in this | ||
* // example) and add as much helpful debugging information to that error as | ||
* // possible. | ||
* return true; | ||
* }, | ||
* 'unexpected error', | ||
* ); | ||
* ``` | ||
* | ||
* `error` cannot be a string. If a string is provided as the second | ||
* argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same | ||
* message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using | ||
* a string as the second argument gets considered: | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* function throwingFirst() { | ||
* throw new Error('First'); | ||
* } | ||
* | ||
* function throwingSecond() { | ||
* throw new Error('Second'); | ||
* } | ||
* | ||
* function notThrowing() {} | ||
* | ||
* // The second argument is a string and the input function threw an Error. | ||
* // The first case will not throw as it does not match for the error message | ||
* // thrown by the input function! | ||
* assert.throws(throwingFirst, 'Second'); | ||
* // In the next example the message has no benefit over the message from the | ||
* // error and since it is not clear if the user intended to actually match | ||
* // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. | ||
* assert.throws(throwingSecond, 'Second'); | ||
* // TypeError [ERR_AMBIGUOUS_ARGUMENT] | ||
* | ||
* // The string is only used (as message) in case the function does not throw: | ||
* assert.throws(notThrowing, 'Second'); | ||
* // AssertionError [ERR_ASSERTION]: Missing expected exception: Second | ||
* | ||
* // If it was intended to match for the error message do this instead: | ||
* // It does not throw because the error messages match. | ||
* assert.throws(throwingSecond, /Second$/); | ||
* | ||
* // If the error message does not match, an AssertionError is thrown. | ||
* assert.throws(throwingFirst, /Second$/); | ||
* // AssertionError [ERR_ASSERTION] | ||
* ``` | ||
* | ||
* Due to the confusing error-prone notation, avoid a string as the second | ||
* argument. | ||
* @since v0.1.21 | ||
*/ | ||
function throws(block: () => unknown, message?: string | Error): void; | ||
function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; | ||
/** | ||
* Asserts that the function `fn` does not throw an error. | ||
* | ||
* Using `assert.doesNotThrow()` is actually not useful because there | ||
* is no benefit in catching an error and then rethrowing it. Instead, consider | ||
* adding a comment next to the specific code path that should not throw and keep | ||
* error messages as expressive as possible. | ||
* | ||
* When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. | ||
* | ||
* If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a | ||
* different type, or if the `error` parameter is undefined, the error is | ||
* propagated back to the caller. | ||
* | ||
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), | ||
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation | ||
* function. See {@link throws} for more details. | ||
* | ||
* The following, for instance, will throw the `TypeError` because there is no | ||
* matching error type in the assertion: | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.doesNotThrow( | ||
* () => { | ||
* throw new TypeError('Wrong value'); | ||
* }, | ||
* SyntaxError, | ||
* ); | ||
* ``` | ||
* | ||
* However, the following will result in an `AssertionError` with the message | ||
* 'Got unwanted exception...': | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.doesNotThrow( | ||
* () => { | ||
* throw new TypeError('Wrong value'); | ||
* }, | ||
* TypeError, | ||
* ); | ||
* ``` | ||
* | ||
* If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.doesNotThrow( | ||
* () => { | ||
* throw new TypeError('Wrong value'); | ||
* }, | ||
* /Wrong value/, | ||
* 'Whoops', | ||
* ); | ||
* // Throws: AssertionError: Got unwanted exception: Whoops | ||
* ``` | ||
* @since v0.1.21 | ||
*/ | ||
function doesNotThrow(block: () => unknown, message?: string | Error): void; | ||
function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; | ||
/** | ||
* Throws `value` if `value` is not `undefined` or `null`. This is useful when | ||
* testing the `error` argument in callbacks. The stack trace contains all frames | ||
* from the error passed to `ifError()` including the potential new frames for`ifError()` itself. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.ifError(null); | ||
* // OK | ||
* assert.ifError(0); | ||
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 | ||
* assert.ifError('error'); | ||
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' | ||
* assert.ifError(new Error()); | ||
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error | ||
* | ||
* // Create some random error frames. | ||
* let err; | ||
* (function errorFrame() { | ||
* err = new Error('test error'); | ||
* })(); | ||
* | ||
* (function ifErrorFrame() { | ||
* assert.ifError(err); | ||
* })(); | ||
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error | ||
* // at ifErrorFrame | ||
* // at errorFrame | ||
* ``` | ||
* @since v0.1.97 | ||
*/ | ||
function ifError(value: unknown): asserts value is null | undefined; | ||
/** | ||
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately | ||
* calls the function and awaits the returned promise to complete. It will then | ||
* 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` error. In both cases the error | ||
* handler is skipped. | ||
* | ||
* Besides the async nature to await the completion behaves identically to {@link throws}. | ||
* | ||
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), | ||
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, | ||
* an object where each property will be tested for, or an instance of error where | ||
* each property will be tested for including the non-enumerable `message` and`name` properties. | ||
* | ||
* If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* await assert.rejects( | ||
* async () => { | ||
* throw new TypeError('Wrong value'); | ||
* }, | ||
* { | ||
* name: 'TypeError', | ||
* message: 'Wrong value', | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* await assert.rejects( | ||
* async () => { | ||
* throw new TypeError('Wrong value'); | ||
* }, | ||
* (err) => { | ||
* assert.strictEqual(err.name, 'TypeError'); | ||
* assert.strictEqual(err.message, 'Wrong value'); | ||
* return true; | ||
* }, | ||
* ); | ||
* ``` | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.rejects( | ||
* Promise.reject(new Error('Wrong value')), | ||
* Error, | ||
* ).then(() => { | ||
* // ... | ||
* }); | ||
* ``` | ||
* | ||
* `error` cannot be a string. If a string is provided as the second | ||
* argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the | ||
* example in {@link throws} carefully if using a string as the second | ||
* argument gets considered. | ||
* @since v10.0.0 | ||
*/ | ||
function rejects(block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>; | ||
function rejects( | ||
block: (() => Promise<any>) | Promise<any>, | ||
block: (() => Promise<unknown>) | Promise<unknown>, | ||
error: AssertPredicate, | ||
message?: string | Error, | ||
): Promise<void>; | ||
function doesNotReject(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>; | ||
/** | ||
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately | ||
* calls the function and awaits the returned promise to complete. It will then | ||
* check that the promise is not rejected. | ||
* | ||
* 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` error. In both cases | ||
* the error handler is skipped. | ||
* | ||
* Using `assert.doesNotReject()` is actually not useful because there is little | ||
* benefit in catching a rejection and then rejecting it again. Instead, consider | ||
* adding a comment next to the specific code path that should not reject and keep | ||
* error messages as expressive as possible. | ||
* | ||
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), | ||
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation | ||
* function. See {@link throws} for more details. | ||
* | ||
* Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* await assert.doesNotReject( | ||
* async () => { | ||
* throw new TypeError('Wrong value'); | ||
* }, | ||
* SyntaxError, | ||
* ); | ||
* ``` | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) | ||
* .then(() => { | ||
* // ... | ||
* }); | ||
* ``` | ||
* @since v10.0.0 | ||
*/ | ||
function doesNotReject( | ||
block: (() => Promise<any>) | Promise<any>, | ||
block: (() => Promise<unknown>) | Promise<unknown>, | ||
message?: string | Error, | ||
): Promise<void>; | ||
function doesNotReject( | ||
block: (() => Promise<unknown>) | Promise<unknown>, | ||
error: AssertPredicate, | ||
message?: string | Error, | ||
): Promise<void>; | ||
/** | ||
* Expects the `string` input to match the regular expression. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.match('I will fail', /pass/); | ||
* // AssertionError [ERR_ASSERTION]: The input did not match the regular ... | ||
* | ||
* assert.match(123, /pass/); | ||
* // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. | ||
* | ||
* assert.match('I will pass', /pass/); | ||
* // OK | ||
* ``` | ||
* | ||
* If the values do not match, or if the `string` argument is of another type than`string`, an `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` then it will be thrown instead of the `AssertionError`. | ||
* @since v13.6.0, v12.16.0 | ||
*/ | ||
function match(value: string, regExp: RegExp, message?: string | Error): void; | ||
/** | ||
* Expects the `string` input not to match the regular expression. | ||
* | ||
* ```js | ||
* import assert from 'node:assert/strict'; | ||
* | ||
* assert.doesNotMatch('I will fail', /fail/); | ||
* // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... | ||
* | ||
* assert.doesNotMatch(123, /pass/); | ||
* // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. | ||
* | ||
* assert.doesNotMatch('I will pass', /different/); | ||
* // OK | ||
* ``` | ||
* | ||
* If the values do match, or if the `string` argument is of another type than`string`, an `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` then it will be thrown instead of the `AssertionError`. | ||
* @since v13.6.0, v12.16.0 | ||
*/ | ||
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; | ||
const strict: Omit< | ||
typeof assert, | ||
| 'equal' | ||
| 'notEqual' | ||
| 'deepEqual' | ||
| 'notDeepEqual' | ||
| 'ok' | ||
| 'strictEqual' | ||
| 'deepStrictEqual' | ||
| 'ifError' | ||
| 'strict' | ||
> & { | ||
(value: any, message?: string | Error): asserts value; | ||
equal: typeof strictEqual; | ||
notEqual: typeof notStrictEqual; | ||
deepEqual: typeof deepStrictEqual; | ||
notDeepEqual: typeof notDeepStrictEqual; | ||
// Mapped types and assertion functions are incompatible? | ||
// TS2775: Assertions require every name in the call target | ||
// to be declared with an explicit type annotation. | ||
ok: typeof ok; | ||
strictEqual: typeof strictEqual; | ||
deepStrictEqual: typeof deepStrictEqual; | ||
ifError: typeof ifError; | ||
strict: typeof strict; | ||
}; | ||
const strict: | ||
& Omit< | ||
typeof assert, | ||
| "equal" | ||
| "notEqual" | ||
| "deepEqual" | ||
| "notDeepEqual" | ||
| "ok" | ||
| "strictEqual" | ||
| "deepStrictEqual" | ||
| "ifError" | ||
| "strict" | ||
> | ||
& { | ||
(value: unknown, message?: string | Error): asserts value; | ||
equal: typeof strictEqual; | ||
notEqual: typeof notStrictEqual; | ||
deepEqual: typeof deepStrictEqual; | ||
notDeepEqual: typeof notDeepStrictEqual; | ||
// Mapped types and assertion functions are incompatible? | ||
// TS2775: Assertions require every name in the call target | ||
// to be declared with an explicit type annotation. | ||
ok: typeof ok; | ||
strictEqual: typeof strictEqual; | ||
deepStrictEqual: typeof deepStrictEqual; | ||
ifError: typeof ifError; | ||
strict: typeof strict; | ||
}; | ||
} | ||
export = assert; | ||
} | ||
declare module "node:assert" { | ||
import assert = require("assert"); | ||
export = assert; | ||
} |
/** | ||
* Async Hooks module: https://nodejs.org/api/async_hooks.html | ||
* We strongly discourage the use of the `async_hooks` API. | ||
* Other APIs that can cover most of its use cases include: | ||
* | ||
* * `AsyncLocalStorage` tracks async context | ||
* * `process.getActiveResourcesInfo()` tracks active resources | ||
* | ||
* The `node:async_hooks` module provides an API to track asynchronous resources. | ||
* It can be accessed using: | ||
* | ||
* ```js | ||
* import async_hooks from 'node:async_hooks'; | ||
* ``` | ||
* @experimental | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) | ||
*/ | ||
declare module "async_hooks" { | ||
/** | ||
* Returns the asyncId of the current execution context. | ||
* ```js | ||
* import { executionAsyncId } from 'node:async_hooks'; | ||
* import fs from 'node:fs'; | ||
* | ||
* console.log(executionAsyncId()); // 1 - bootstrap | ||
* const path = '.'; | ||
* fs.open(path, 'r', (err, fd) => { | ||
* console.log(executionAsyncId()); // 6 - open() | ||
* }); | ||
* ``` | ||
* | ||
* The ID returned from `executionAsyncId()` is related to execution timing, not | ||
* causality (which is covered by `triggerAsyncId()`): | ||
* | ||
* ```js | ||
* const server = net.createServer((conn) => { | ||
* // Returns the ID of the server, not of the new connection, because the | ||
* // callback runs in the execution scope of the server's MakeCallback(). | ||
* async_hooks.executionAsyncId(); | ||
* | ||
* }).listen(port, () => { | ||
* // Returns the ID of a TickObject (process.nextTick()) because all | ||
* // callbacks passed to .listen() are wrapped in a nextTick(). | ||
* async_hooks.executionAsyncId(); | ||
* }); | ||
* ``` | ||
* | ||
* Promise contexts may not get precise `executionAsyncIds` by default. | ||
* See the section on `promise execution tracking`. | ||
* @since v8.1.0 | ||
* @return The `asyncId` of the current execution context. Useful to track when something calls. | ||
*/ | ||
function executionAsyncId(): number; | ||
/** | ||
* The resource representing the current execution. | ||
* Useful to store data within the resource. | ||
* | ||
* Resource objects returned by `executionAsyncResource()` are most often internal | ||
@@ -21,10 +60,66 @@ * Node.js handle objects with undocumented APIs. Using any functions or properties | ||
* but having an object representing the top-level can be helpful. | ||
* | ||
* ```js | ||
* import { open } from 'node:fs'; | ||
* import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; | ||
* | ||
* console.log(executionAsyncId(), executionAsyncResource()); // 1 {} | ||
* open(new URL(import.meta.url), 'r', (err, fd) => { | ||
* console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap | ||
* }); | ||
* ``` | ||
* | ||
* This can be used to implement continuation local storage without the | ||
* use of a tracking `Map` to store the metadata: | ||
* | ||
* ```js | ||
* import { createServer } from 'node:http'; | ||
* import { | ||
* executionAsyncId, | ||
* executionAsyncResource, | ||
* createHook, | ||
* } from 'async_hooks'; | ||
* const sym = Symbol('state'); // Private symbol to avoid pollution | ||
* | ||
* createHook({ | ||
* init(asyncId, type, triggerAsyncId, resource) { | ||
* const cr = executionAsyncResource(); | ||
* if (cr) { | ||
* resource[sym] = cr[sym]; | ||
* } | ||
* }, | ||
* }).enable(); | ||
* | ||
* const server = createServer((req, res) => { | ||
* executionAsyncResource()[sym] = { state: req.url }; | ||
* setTimeout(function() { | ||
* res.end(JSON.stringify(executionAsyncResource()[sym])); | ||
* }, 100); | ||
* }).listen(3000); | ||
* ``` | ||
* @since v13.9.0, v12.17.0 | ||
* @return The resource representing the current execution. Useful to store data within the resource. | ||
*/ | ||
function executionAsyncResource(): object; | ||
/** | ||
* Returns the ID of the resource responsible for calling the callback that is currently being executed. | ||
* ```js | ||
* const server = net.createServer((conn) => { | ||
* // The resource that caused (or triggered) this callback to be called | ||
* // was that of the new connection. Thus the return value of triggerAsyncId() | ||
* // is the asyncId of "conn". | ||
* async_hooks.triggerAsyncId(); | ||
* | ||
* }).listen(port, () => { | ||
* // Even though all callbacks passed to .listen() are wrapped in a nextTick() | ||
* // the callback itself exists because the call to the server's .listen() | ||
* // was made. So the return value would be the ID of the server. | ||
* async_hooks.triggerAsyncId(); | ||
* }); | ||
* ``` | ||
* | ||
* Promise contexts may not get valid `triggerAsyncId`s by default. See | ||
* the section on `promise execution tracking`. | ||
* @return The ID of the resource responsible for calling the callback that is currently being executed. | ||
*/ | ||
function triggerAsyncId(): number; | ||
interface HookCallbacks { | ||
@@ -39,3 +134,2 @@ /** | ||
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; | ||
/** | ||
@@ -47,3 +141,2 @@ * When an asynchronous operation is initiated or completes a callback is called to notify the user. | ||
before?(asyncId: number): void; | ||
/** | ||
@@ -54,3 +147,2 @@ * Called immediately after the callback specified in before is completed. | ||
after?(asyncId: number): void; | ||
/** | ||
@@ -62,3 +154,2 @@ * Called when a promise has resolve() called. This may not be in the same execution id | ||
promiseResolve?(asyncId: number): void; | ||
/** | ||
@@ -70,3 +161,2 @@ * Called after the resource corresponding to asyncId is destroyed | ||
} | ||
interface AsyncHook { | ||
@@ -77,3 +167,2 @@ /** | ||
enable(): this; | ||
/** | ||
@@ -84,30 +173,96 @@ * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. | ||
} | ||
/** | ||
* Registers functions to be called for different lifetime events of each async operation. | ||
* @param options the callbacks to register | ||
* @return an AsyncHooks instance used for disabling and enabling hooks | ||
* Registers functions to be called for different lifetime events of each async | ||
* operation. | ||
* | ||
* The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the | ||
* respective asynchronous event during a resource's lifetime. | ||
* | ||
* All callbacks are optional. For example, if only resource cleanup needs to | ||
* be tracked, then only the `destroy` callback needs to be passed. The | ||
* specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. | ||
* | ||
* ```js | ||
* import { createHook } from 'node:async_hooks'; | ||
* | ||
* const asyncHook = createHook({ | ||
* init(asyncId, type, triggerAsyncId, resource) { }, | ||
* destroy(asyncId) { }, | ||
* }); | ||
* ``` | ||
* | ||
* The callbacks will be inherited via the prototype chain: | ||
* | ||
* ```js | ||
* class MyAsyncCallbacks { | ||
* init(asyncId, type, triggerAsyncId, resource) { } | ||
* destroy(asyncId) {} | ||
* } | ||
* | ||
* class MyAddedCallbacks extends MyAsyncCallbacks { | ||
* before(asyncId) { } | ||
* after(asyncId) { } | ||
* } | ||
* | ||
* const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); | ||
* ``` | ||
* | ||
* Because promises are asynchronous resources whose lifecycle is tracked | ||
* via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. | ||
* @since v8.1.0 | ||
* @param callbacks The `Hook Callbacks` to register | ||
* @return Instance used for disabling and enabling hooks | ||
*/ | ||
function createHook(options: HookCallbacks): AsyncHook; | ||
function createHook(callbacks: HookCallbacks): AsyncHook; | ||
interface AsyncResourceOptions { | ||
/** | ||
* The ID of the execution context that created this async event. | ||
* Default: `executionAsyncId()` | ||
*/ | ||
triggerAsyncId?: number; | ||
/** | ||
* Disables automatic `emitDestroy` when the object is garbage collected. | ||
* This usually does not need to be set (even if `emitDestroy` is called | ||
* manually), unless the resource's `asyncId` is retrieved and the | ||
* sensitive API's `emitDestroy` is called with it. | ||
* Default: `false` | ||
*/ | ||
requireManualDestroy?: boolean; | ||
/** | ||
* The ID of the execution context that created this async event. | ||
* @default executionAsyncId() | ||
*/ | ||
triggerAsyncId?: number | undefined; | ||
/** | ||
* Disables automatic `emitDestroy` when the object is garbage collected. | ||
* This usually does not need to be set (even if `emitDestroy` is called | ||
* manually), unless the resource's `asyncId` is retrieved and the | ||
* sensitive API's `emitDestroy` is called with it. | ||
* @default false | ||
*/ | ||
requireManualDestroy?: boolean | undefined; | ||
} | ||
/** | ||
* The class AsyncResource was designed to be extended by the embedder's async resources. | ||
* Using this users can easily trigger the lifetime events of their own resources. | ||
* The class `AsyncResource` is designed to be extended by the embedder's async | ||
* resources. Using this, users can easily trigger the lifetime events of their | ||
* own resources. | ||
* | ||
* The `init` hook will trigger when an `AsyncResource` is instantiated. | ||
* | ||
* The following is an overview of the `AsyncResource` API. | ||
* | ||
* ```js | ||
* import { AsyncResource, executionAsyncId } from 'node:async_hooks'; | ||
* | ||
* // AsyncResource() is meant to be extended. Instantiating a | ||
* // new AsyncResource() also triggers init. If triggerAsyncId is omitted then | ||
* // async_hook.executionAsyncId() is used. | ||
* const asyncResource = new AsyncResource( | ||
* type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, | ||
* ); | ||
* | ||
* // Run a function in the execution context of the resource. This will | ||
* // * establish the context of the resource | ||
* // * trigger the AsyncHooks before callbacks | ||
* // * call the provided function `fn` with the supplied arguments | ||
* // * trigger the AsyncHooks after callbacks | ||
* // * restore the original execution context | ||
* asyncResource.runInAsyncScope(fn, thisArg, ...args); | ||
* | ||
* // Call AsyncHooks destroy callbacks. | ||
* asyncResource.emitDestroy(); | ||
* | ||
* // Return the unique ID assigned to the AsyncResource instance. | ||
* asyncResource.asyncId(); | ||
* | ||
* // Return the trigger ID for the AsyncResource instance. | ||
* asyncResource.triggerAsyncId(); | ||
* ``` | ||
*/ | ||
@@ -122,111 +277,266 @@ class AsyncResource { | ||
* this async event (default: `executionAsyncId()`), or an | ||
* AsyncResourceOptions object (since 9.3) | ||
* AsyncResourceOptions object (since v9.3.0) | ||
*/ | ||
constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); | ||
constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); | ||
/** | ||
* Binds the given function to the current execution context. | ||
* @since v14.8.0, v12.19.0 | ||
* @param fn The function to bind to the current execution context. | ||
* @param type An optional name to associate with the underlying `AsyncResource`. | ||
*/ | ||
static bind<Func extends (...args: any[]) => any>(fn: Func, type?: string): Func & { asyncResource: AsyncResource }; | ||
static bind<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>( | ||
fn: Func, | ||
type?: string, | ||
thisArg?: ThisArg, | ||
): Func; | ||
/** | ||
* Binds the given function to execute to this `AsyncResource`'s scope. | ||
* @since v14.8.0, v12.19.0 | ||
* @param fn The function to bind to the current `AsyncResource`. | ||
*/ | ||
bind<Func extends (...args: any[]) => any>(fn: Func): Func & { asyncResource: AsyncResource }; | ||
bind<Func extends (...args: any[]) => any>(fn: Func): Func; | ||
/** | ||
* Call the provided function with the provided arguments in the | ||
* execution context of the async resource. This will establish the | ||
* context, trigger the AsyncHooks before callbacks, call the function, | ||
* trigger the AsyncHooks after callbacks, and then restore the original | ||
* execution context. | ||
* @param fn The function to call in the execution context of this | ||
* async resource. | ||
* Call the provided function with the provided arguments in the execution context | ||
* of the async resource. This will establish the context, trigger the AsyncHooks | ||
* before callbacks, call the function, trigger the AsyncHooks after callbacks, and | ||
* then restore the original execution context. | ||
* @since v9.6.0 | ||
* @param fn The function to call in the execution context of this async resource. | ||
* @param thisArg The receiver to be used for the function call. | ||
* @param args Optional arguments to pass to the function. | ||
*/ | ||
runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; | ||
runInAsyncScope<This, Result>( | ||
fn: (this: This, ...args: any[]) => Result, | ||
thisArg?: This, | ||
...args: any[] | ||
): Result; | ||
/** | ||
* Call AsyncHooks destroy callbacks. | ||
* Call all `destroy` hooks. This should only ever be called once. An error will | ||
* be thrown if it is called more than once. This **must** be manually called. If | ||
* the resource is left to be collected by the GC then the `destroy` hooks will | ||
* never be called. | ||
* @return A reference to `asyncResource`. | ||
*/ | ||
emitDestroy(): void; | ||
emitDestroy(): this; | ||
/** | ||
* @return the unique ID assigned to this AsyncResource instance. | ||
* @return The unique `asyncId` assigned to the resource. | ||
*/ | ||
asyncId(): number; | ||
/** | ||
* @return the trigger ID for this AsyncResource instance. | ||
* @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. | ||
*/ | ||
triggerAsyncId(): number; | ||
} | ||
/** | ||
* When having multiple instances of `AsyncLocalStorage`, they are independent | ||
* from each other. It is safe to instantiate this class multiple times. | ||
* This class creates stores that stay coherent through asynchronous operations. | ||
* | ||
* While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory | ||
* safe implementation that involves significant optimizations that are non-obvious | ||
* to implement. | ||
* | ||
* The following example uses `AsyncLocalStorage` to build a simple logger | ||
* that assigns IDs to incoming HTTP requests and includes them in messages | ||
* logged within each request. | ||
* | ||
* ```js | ||
* import http from 'node:http'; | ||
* import { AsyncLocalStorage } from 'node:async_hooks'; | ||
* | ||
* const asyncLocalStorage = new AsyncLocalStorage(); | ||
* | ||
* function logWithId(msg) { | ||
* const id = asyncLocalStorage.getStore(); | ||
* console.log(`${id !== undefined ? id : '-'}:`, msg); | ||
* } | ||
* | ||
* let idSeq = 0; | ||
* http.createServer((req, res) => { | ||
* asyncLocalStorage.run(idSeq++, () => { | ||
* logWithId('start'); | ||
* // Imagine any chain of async operations here | ||
* setImmediate(() => { | ||
* logWithId('finish'); | ||
* res.end(); | ||
* }); | ||
* }); | ||
* }).listen(8080); | ||
* | ||
* http.get('http://localhost:8080'); | ||
* http.get('http://localhost:8080'); | ||
* // Prints: | ||
* // 0: start | ||
* // 1: start | ||
* // 0: finish | ||
* // 1: finish | ||
* ``` | ||
* | ||
* Each instance of `AsyncLocalStorage` maintains an independent storage context. | ||
* Multiple instances can safely exist simultaneously without risk of interfering | ||
* with each other's data. | ||
* @since v13.10.0, v12.17.0 | ||
*/ | ||
class AsyncLocalStorage<T> { | ||
/** | ||
* This method disables the instance of `AsyncLocalStorage`. All subsequent calls | ||
* to `asyncLocalStorage.getStore()` will return `undefined` until | ||
* `asyncLocalStorage.run()` is called again. | ||
* 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. | ||
*/ | ||
static bind<Func extends (...args: any[]) => any>(fn: Func): Func; | ||
/** | ||
* Captures the current execution context and returns a function that accepts a | ||
* function as an argument. Whenever the returned function is called, it | ||
* calls the function passed to it within the captured context. | ||
* | ||
* ```js | ||
* const asyncLocalStorage = new AsyncLocalStorage(); | ||
* const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); | ||
* const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); | ||
* console.log(result); // returns 123 | ||
* ``` | ||
* | ||
* AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple | ||
* async context tracking purposes, for example: | ||
* | ||
* ```js | ||
* class Foo { | ||
* #runInAsyncScope = AsyncLocalStorage.snapshot(); | ||
* | ||
* get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } | ||
* } | ||
* | ||
* const foo = asyncLocalStorage.run(123, () => new Foo()); | ||
* 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; | ||
/** | ||
* Disables the instance of `AsyncLocalStorage`. All subsequent calls | ||
* to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. | ||
* | ||
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the | ||
* instance will be exited. | ||
* | ||
* Calling `asyncLocalStorage.disable()` is required before the | ||
* `asyncLocalStorage` can be garbage collected. This does not apply to stores | ||
* Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores | ||
* provided by the `asyncLocalStorage`, as those objects are garbage collected | ||
* along with the corresponding async resources. | ||
* | ||
* This method is to be used when the `asyncLocalStorage` is not in use anymore | ||
* Use this method when the `asyncLocalStorage` is not in use anymore | ||
* in the current process. | ||
* @since v13.10.0, v12.17.0 | ||
* @experimental | ||
*/ | ||
disable(): void; | ||
/** | ||
* This method returns the current store. If this method is called outside of an | ||
* asynchronous context initialized by calling `asyncLocalStorage.run`, it will | ||
* return `undefined`. | ||
* Returns the current store. | ||
* If called outside of an asynchronous context initialized by | ||
* calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it | ||
* returns `undefined`. | ||
* @since v13.10.0, v12.17.0 | ||
*/ | ||
getStore(): T | undefined; | ||
/** | ||
* This methods runs a function synchronously within a context and return its | ||
* return value. The store is not accessible outside of the callback function or | ||
* the asynchronous operations created within the callback. | ||
* Runs a function synchronously within a context and returns its | ||
* return value. The store is not accessible outside of the callback function. | ||
* The store is accessible to any asynchronous operations created within the | ||
* callback. | ||
* | ||
* Optionally, arguments can be passed to the function. They will be passed to the | ||
* callback function. | ||
* The optional `args` are passed to the callback function. | ||
* | ||
* I the callback function throws an error, it will be thrown by `run` too. The | ||
* stacktrace will not be impacted by this call and the context will be exited. | ||
* If the callback function throws an error, the error is thrown by `run()` too. | ||
* The stacktrace is not impacted by this call and the context is exited. | ||
* | ||
* Example: | ||
* | ||
* ```js | ||
* const store = { id: 2 }; | ||
* try { | ||
* asyncLocalStorage.run(store, () => { | ||
* asyncLocalStorage.getStore(); // Returns the store object | ||
* setTimeout(() => { | ||
* asyncLocalStorage.getStore(); // Returns the store object | ||
* }, 200); | ||
* throw new Error(); | ||
* }); | ||
* } catch (e) { | ||
* asyncLocalStorage.getStore(); // Returns undefined | ||
* // The error will be caught here | ||
* } | ||
* ``` | ||
* @since v13.10.0, v12.17.0 | ||
*/ | ||
// TODO: Apply generic vararg once available | ||
run<R>(store: T, callback: (...args: any[]) => R, ...args: any[]): R; | ||
run<R>(store: T, callback: () => R): R; | ||
run<R, TArgs extends any[]>(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; | ||
/** | ||
* This methods runs a function synchronously outside of a context and return its | ||
* return value. The store is not accessible within the callback function or the | ||
* asynchronous operations created within the callback. | ||
* Runs a function synchronously outside of a context and returns its | ||
* return value. The store is not accessible within the callback function or | ||
* the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. | ||
* | ||
* Optionally, arguments can be passed to the function. They will be passed to the | ||
* callback function. | ||
* The optional `args` are passed to the callback function. | ||
* | ||
* If the callback function throws an error, it will be thrown by `exit` too. The | ||
* stacktrace will not be impacted by this call and the context will be | ||
* re-entered. | ||
* If the callback function throws an error, the error is thrown by `exit()` too. | ||
* The stacktrace is not impacted by this call and the context is re-entered. | ||
* | ||
* Example: | ||
* | ||
* ```js | ||
* // Within a call to run | ||
* try { | ||
* asyncLocalStorage.getStore(); // Returns the store object or value | ||
* asyncLocalStorage.exit(() => { | ||
* asyncLocalStorage.getStore(); // Returns undefined | ||
* throw new Error(); | ||
* }); | ||
* } catch (e) { | ||
* asyncLocalStorage.getStore(); // Returns the same object or value | ||
* // The error will be caught here | ||
* } | ||
* ``` | ||
* @since v13.10.0, v12.17.0 | ||
* @experimental | ||
*/ | ||
// TODO: Apply generic vararg once available | ||
exit<R>(callback: (...args: any[]) => R, ...args: any[]): R; | ||
exit<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R; | ||
/** | ||
* Calling `asyncLocalStorage.enterWith(store)` will transition into the context | ||
* for the remainder of the current synchronous execution and will persist | ||
* through any following asynchronous calls. | ||
* Transitions into the context for the remainder of the current | ||
* synchronous execution and then persists the store through any following | ||
* asynchronous calls. | ||
* | ||
* Example: | ||
* | ||
* ```js | ||
* const store = { id: 1 }; | ||
* // Replaces previous store with the given store object | ||
* asyncLocalStorage.enterWith(store); | ||
* asyncLocalStorage.getStore(); // Returns the store object | ||
* someAsyncOperation(() => { | ||
* asyncLocalStorage.getStore(); // Returns the same object | ||
* }); | ||
* ``` | ||
* | ||
* This transition will continue for the _entire_ synchronous execution. | ||
* This means that if, for example, the context is entered within an event | ||
* handler subsequent event handlers will also run within that context unless | ||
* specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons | ||
* to use the latter method. | ||
* | ||
* ```js | ||
* const store = { id: 1 }; | ||
* | ||
* emitter.on('my-event', () => { | ||
* asyncLocalStorage.enterWith(store); | ||
* }); | ||
* emitter.on('my-event', () => { | ||
* asyncLocalStorage.getStore(); // Returns the same object | ||
* }); | ||
* | ||
* asyncLocalStorage.getStore(); // Returns undefined | ||
* emitter.emit('my-event'); | ||
* asyncLocalStorage.getStore(); // Returns the same object | ||
* ``` | ||
* @since v13.11.0, v12.17.0 | ||
* @experimental | ||
*/ | ||
@@ -236,1 +546,4 @@ enterWith(store: T): void; | ||
} | ||
declare module "node:async_hooks" { | ||
export * from "async_hooks"; | ||
} |
@@ -0,35 +1,285 @@ | ||
/** | ||
* 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` 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 | ||
* server ports. | ||
* | ||
* ```js | ||
* import cluster from 'node:cluster'; | ||
* import http from 'node:http'; | ||
* import { availableParallelism } from 'node:os'; | ||
* import process from 'node:process'; | ||
* | ||
* const numCPUs = availableParallelism(); | ||
* | ||
* if (cluster.isPrimary) { | ||
* console.log(`Primary ${process.pid} is running`); | ||
* | ||
* // Fork workers. | ||
* for (let i = 0; i < numCPUs; i++) { | ||
* cluster.fork(); | ||
* } | ||
* | ||
* cluster.on('exit', (worker, code, signal) => { | ||
* console.log(`worker ${worker.process.pid} died`); | ||
* }); | ||
* } else { | ||
* // Workers can share any TCP connection | ||
* // In this case it is an HTTP server | ||
* http.createServer((req, res) => { | ||
* res.writeHead(200); | ||
* res.end('hello world\n'); | ||
* }).listen(8000); | ||
* | ||
* console.log(`Worker ${process.pid} started`); | ||
* } | ||
* ``` | ||
* | ||
* Running Node.js will now share port 8000 between the workers: | ||
* | ||
* ```console | ||
* $ node server.js | ||
* Primary 3596 is running | ||
* Worker 4324 started | ||
* Worker 4520 started | ||
* Worker 6056 started | ||
* Worker 5644 started | ||
* ``` | ||
* | ||
* 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/v20.2.0/lib/cluster.js) | ||
*/ | ||
declare module "cluster" { | ||
import * as child from "child_process"; | ||
import * as events from "events"; | ||
import * as net from "net"; | ||
// interfaces | ||
interface ClusterSettings { | ||
execArgv?: string[]; // default: process.execArgv | ||
exec?: string; | ||
args?: string[]; | ||
silent?: boolean; | ||
stdio?: any[]; | ||
uid?: number; | ||
gid?: number; | ||
inspectPort?: number | (() => number); | ||
import * as child from "node:child_process"; | ||
import EventEmitter = require("node:events"); | ||
import * as net from "node:net"; | ||
type SerializationType = "json" | "advanced"; | ||
export interface ClusterSettings { | ||
execArgv?: string[] | undefined; // default: process.execArgv | ||
exec?: string | undefined; | ||
args?: string[] | undefined; | ||
silent?: boolean | undefined; | ||
stdio?: any[] | undefined; | ||
uid?: number | undefined; | ||
gid?: number | undefined; | ||
inspectPort?: number | (() => number) | undefined; | ||
serialization?: SerializationType | undefined; | ||
cwd?: string | undefined; | ||
windowsHide?: boolean | undefined; | ||
} | ||
interface Address { | ||
export interface Address { | ||
address: string; | ||
port: number; | ||
addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" | ||
addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" | ||
} | ||
class Worker extends events.EventEmitter { | ||
/** | ||
* A `Worker` object contains all public information and method about a worker. | ||
* In the primary it can be obtained using `cluster.workers`. In a worker | ||
* it can be obtained using `cluster.worker`. | ||
* @since v0.7.0 | ||
*/ | ||
export class Worker extends EventEmitter { | ||
/** | ||
* Each new worker is given its own unique id, this id is stored in the`id`. | ||
* | ||
* While a worker is alive, this is the key that indexes it in`cluster.workers`. | ||
* @since v0.8.0 | ||
*/ | ||
id: number; | ||
/** | ||
* All workers are created using `child_process.fork()`, the returned object | ||
* from this function is stored as `.process`. In a worker, the global `process`is stored. | ||
* | ||
* See: `Child Process module`. | ||
* | ||
* Workers will call `process.exit(0)` if the `'disconnect'` event occurs | ||
* on `process` and `.exitedAfterDisconnect` is not `true`. This protects against | ||
* accidental disconnection. | ||
* @since v0.7.0 | ||
*/ | ||
process: child.ChildProcess; | ||
send(message: child.Serializable, sendHandle?: child.SendHandle, callback?: (error: Error | null) => void): boolean; | ||
/** | ||
* 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()`. | ||
* | ||
* In a worker, this sends a message to the primary. It is identical to`process.send()`. | ||
* | ||
* This example will echo back all messages from the primary: | ||
* | ||
* ```js | ||
* if (cluster.isPrimary) { | ||
* const worker = cluster.fork(); | ||
* worker.send('hi there'); | ||
* | ||
* } else if (cluster.isWorker) { | ||
* process.on('message', (msg) => { | ||
* process.send(msg); | ||
* }); | ||
* } | ||
* ``` | ||
* @since v0.7.0 | ||
* @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: child.Serializable, callback?: (error: Error | null) => void): boolean; | ||
send( | ||
message: child.Serializable, | ||
sendHandle: child.SendHandle, | ||
callback?: (error: Error | null) => void, | ||
): boolean; | ||
send( | ||
message: child.Serializable, | ||
sendHandle: child.SendHandle, | ||
options?: child.MessageOptions, | ||
callback?: (error: Error | null) => void, | ||
): boolean; | ||
/** | ||
* This function will kill the worker. In the primary worker, it does this by | ||
* disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. | ||
* | ||
* The `kill()` function kills the worker process without waiting for a graceful | ||
* disconnect, it has the same behavior as `worker.process.kill()`. | ||
* | ||
* 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()`. | ||
* @since v0.9.12 | ||
* @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. | ||
*/ | ||
kill(signal?: string): void; | ||
destroy(signal?: string): void; | ||
/** | ||
* In a worker, this function will close all servers, wait for the `'close'` event | ||
* on those servers, and then disconnect the IPC channel. | ||
* | ||
* In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. | ||
* | ||
* Causes `.exitedAfterDisconnect` to be set. | ||
* | ||
* After a server is closed, it will no longer accept new connections, | ||
* but connections may be accepted by any other listening worker. Existing | ||
* connections will be allowed to close as usual. When no more connections exist, | ||
* see `server.close()`, the IPC channel to the worker will close allowing it | ||
* to die gracefully. | ||
* | ||
* The above applies _only_ to server connections, client connections are not | ||
* automatically closed by workers, and disconnect does not wait for them to close | ||
* before exiting. | ||
* | ||
* In a worker, `process.disconnect` exists, but it is not this function; | ||
* it is `disconnect()`. | ||
* | ||
* Because long living server connections may block workers from disconnecting, it | ||
* may be useful to send a message, so application specific actions may be taken to | ||
* close them. It also may be useful to implement a timeout, killing a worker if | ||
* the `'disconnect'` event has not been emitted after some time. | ||
* | ||
* ```js | ||
* if (cluster.isPrimary) { | ||
* const worker = cluster.fork(); | ||
* let timeout; | ||
* | ||
* worker.on('listening', (address) => { | ||
* worker.send('shutdown'); | ||
* worker.disconnect(); | ||
* timeout = setTimeout(() => { | ||
* worker.kill(); | ||
* }, 2000); | ||
* }); | ||
* | ||
* worker.on('disconnect', () => { | ||
* clearTimeout(timeout); | ||
* }); | ||
* | ||
* } else if (cluster.isWorker) { | ||
* const net = require('node:net'); | ||
* const server = net.createServer((socket) => { | ||
* // Connections never end | ||
* }); | ||
* | ||
* server.listen(8000); | ||
* | ||
* process.on('message', (msg) => { | ||
* if (msg === 'shutdown') { | ||
* // Initiate graceful close of any connections to server | ||
* } | ||
* }); | ||
* } | ||
* ``` | ||
* @since v0.7.7 | ||
* @return A reference to `worker`. | ||
*/ | ||
disconnect(): void; | ||
/** | ||
* 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 | ||
* has been created. It is disconnected after the `'disconnect'` event is emitted. | ||
* @since v0.11.14 | ||
*/ | ||
isConnected(): boolean; | ||
/** | ||
* This function returns `true` if the worker's process has terminated (either | ||
* because of exiting or being signaled). Otherwise, it returns `false`. | ||
* | ||
* ```js | ||
* import cluster from 'node:cluster'; | ||
* import http from 'node:http'; | ||
* import { availableParallelism } from 'node:os'; | ||
* import process from 'node:process'; | ||
* | ||
* const numCPUs = availableParallelism(); | ||
* | ||
* if (cluster.isPrimary) { | ||
* console.log(`Primary ${process.pid} is running`); | ||
* | ||
* // Fork workers. | ||
* for (let i = 0; i < numCPUs; i++) { | ||
* cluster.fork(); | ||
* } | ||
* | ||
* cluster.on('fork', (worker) => { | ||
* console.log('worker is dead:', worker.isDead()); | ||
* }); | ||
* | ||
* cluster.on('exit', (worker, code, signal) => { | ||
* console.log('worker is dead:', worker.isDead()); | ||
* }); | ||
* } else { | ||
* // Workers can share any TCP connection. In this case, it is an HTTP server. | ||
* http.createServer((req, res) => { | ||
* res.writeHead(200); | ||
* res.end(`Current process\n ${process.pid}`); | ||
* process.kill(process.pid); | ||
* }).listen(8000); | ||
* } | ||
* ``` | ||
* @since v0.11.14 | ||
*/ | ||
isDead(): boolean; | ||
/** | ||
* This property is `true` if the worker exited due to `.disconnect()`. | ||
* If the worker exited any other way, it is `false`. If the | ||
* worker has not exited, it is `undefined`. | ||
* | ||
* The boolean `worker.exitedAfterDisconnect` allows distinguishing between | ||
* voluntary and accidental exit, the primary may choose not to respawn a worker | ||
* based on this value. | ||
* | ||
* ```js | ||
* cluster.on('exit', (worker, code, signal) => { | ||
* if (worker.exitedAfterDisconnect === true) { | ||
* console.log('Oh, it was just voluntary – no need to worry'); | ||
* } | ||
* }); | ||
* | ||
* // kill worker | ||
* worker.kill(); | ||
* ``` | ||
* @since v6.0.0 | ||
*/ | ||
exitedAfterDisconnect: boolean; | ||
/** | ||
@@ -49,5 +299,4 @@ * events.EventEmitter | ||
addListener(event: "listening", listener: (address: Address) => void): this; | ||
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
addListener(event: "online", listener: () => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -60,3 +309,2 @@ emit(event: "disconnect"): boolean; | ||
emit(event: "online"): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -67,5 +315,4 @@ on(event: "disconnect", listener: () => void): this; | ||
on(event: "listening", listener: (address: Address) => void): this; | ||
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
on(event: "online", listener: () => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -76,5 +323,4 @@ once(event: "disconnect", listener: () => void): this; | ||
once(event: "listening", listener: (address: Address) => void): this; | ||
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
once(event: "online", listener: () => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -85,5 +331,4 @@ prependListener(event: "disconnect", listener: () => void): this; | ||
prependListener(event: "listening", listener: (address: Address) => void): this; | ||
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
prependListener(event: "online", listener: () => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -94,21 +339,24 @@ prependOnceListener(event: "disconnect", listener: () => void): this; | ||
prependOnceListener(event: "listening", listener: (address: Address) => void): this; | ||
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
prependOnceListener(event: "online", listener: () => void): this; | ||
} | ||
interface Cluster extends events.EventEmitter { | ||
Worker: Worker; | ||
export interface Cluster extends EventEmitter { | ||
disconnect(callback?: () => void): void; | ||
fork(env?: any): Worker; | ||
isMaster: boolean; | ||
isWorker: boolean; | ||
/** @deprecated since v16.0.0 - use isPrimary. */ | ||
readonly isMaster: boolean; | ||
readonly isPrimary: boolean; | ||
readonly isWorker: boolean; | ||
schedulingPolicy: number; | ||
settings: ClusterSettings; | ||
readonly settings: ClusterSettings; | ||
/** @deprecated since v16.0.0 - use setupPrimary. */ | ||
setupMaster(settings?: ClusterSettings): void; | ||
worker?: Worker; | ||
workers?: NodeJS.Dict<Worker>; | ||
/** | ||
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. | ||
*/ | ||
setupPrimary(settings?: ClusterSettings): void; | ||
readonly worker?: Worker | undefined; | ||
readonly workers?: NodeJS.Dict<Worker> | undefined; | ||
readonly SCHED_NONE: number; | ||
readonly SCHED_RR: number; | ||
/** | ||
@@ -129,6 +377,8 @@ * events.EventEmitter | ||
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; | ||
addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
addListener( | ||
event: "message", | ||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, | ||
): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
addListener(event: "online", listener: (worker: Worker) => void): this; | ||
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -142,3 +392,2 @@ emit(event: "disconnect", worker: Worker): boolean; | ||
emit(event: "setup", settings: ClusterSettings): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -149,6 +398,5 @@ on(event: "disconnect", listener: (worker: Worker) => void): this; | ||
on(event: "listening", listener: (worker: Worker, address: Address) => void): this; | ||
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
on(event: "online", listener: (worker: Worker) => void): this; | ||
on(event: "setup", listener: (settings: ClusterSettings) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -159,6 +407,5 @@ once(event: "disconnect", listener: (worker: Worker) => void): this; | ||
once(event: "listening", listener: (worker: Worker, address: Address) => void): this; | ||
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
once(event: "online", listener: (worker: Worker) => void): this; | ||
once(event: "setup", listener: (settings: ClusterSettings) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -169,6 +416,9 @@ prependListener(event: "disconnect", listener: (worker: Worker) => void): this; | ||
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; | ||
prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. | ||
// the handle is a net.Socket or net.Server object, or undefined. | ||
prependListener( | ||
event: "message", | ||
listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, | ||
): this; | ||
prependListener(event: "online", listener: (worker: Worker) => void): this; | ||
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -180,95 +430,15 @@ prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; | ||
// the handle is a net.Socket or net.Server object, or undefined. | ||
prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; | ||
prependOnceListener( | ||
event: "message", | ||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, | ||
): this; | ||
prependOnceListener(event: "online", listener: (worker: Worker) => void): this; | ||
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; | ||
} | ||
const SCHED_NONE: number; | ||
const SCHED_RR: number; | ||
function disconnect(callback?: () => void): void; | ||
function fork(env?: any): Worker; | ||
const isMaster: boolean; | ||
const isWorker: boolean; | ||
let schedulingPolicy: number; | ||
const settings: ClusterSettings; | ||
function setupMaster(settings?: ClusterSettings): void; | ||
const worker: Worker; | ||
const workers: NodeJS.Dict<Worker>; | ||
/** | ||
* events.EventEmitter | ||
* 1. disconnect | ||
* 2. exit | ||
* 3. fork | ||
* 4. listening | ||
* 5. message | ||
* 6. online | ||
* 7. setup | ||
*/ | ||
function addListener(event: string, listener: (...args: any[]) => void): Cluster; | ||
function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; | ||
function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; | ||
function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; | ||
function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; | ||
// the handle is a net.Socket or net.Server object, or undefined. | ||
function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; | ||
function addListener(event: "online", listener: (worker: Worker) => void): Cluster; | ||
function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; | ||
function emit(event: string | symbol, ...args: any[]): boolean; | ||
function emit(event: "disconnect", worker: Worker): boolean; | ||
function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; | ||
function emit(event: "fork", worker: Worker): boolean; | ||
function emit(event: "listening", worker: Worker, address: Address): boolean; | ||
function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; | ||
function emit(event: "online", worker: Worker): boolean; | ||
function emit(event: "setup", settings: ClusterSettings): boolean; | ||
function on(event: string, listener: (...args: any[]) => void): Cluster; | ||
function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; | ||
function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; | ||
function on(event: "fork", listener: (worker: Worker) => void): Cluster; | ||
function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; | ||
function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. | ||
function on(event: "online", listener: (worker: Worker) => void): Cluster; | ||
function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; | ||
function once(event: string, listener: (...args: any[]) => void): Cluster; | ||
function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; | ||
function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; | ||
function once(event: "fork", listener: (worker: Worker) => void): Cluster; | ||
function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; | ||
function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. | ||
function once(event: "online", listener: (worker: Worker) => void): Cluster; | ||
function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; | ||
function removeListener(event: string, listener: (...args: any[]) => void): Cluster; | ||
function removeAllListeners(event?: string): Cluster; | ||
function setMaxListeners(n: number): Cluster; | ||
function getMaxListeners(): number; | ||
function listeners(event: string): Function[]; | ||
function listenerCount(type: string): number; | ||
function prependListener(event: string, listener: (...args: any[]) => void): Cluster; | ||
function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; | ||
function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; | ||
function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; | ||
function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; | ||
// the handle is a net.Socket or net.Server object, or undefined. | ||
function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; | ||
function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; | ||
function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; | ||
function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; | ||
function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; | ||
function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; | ||
function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; | ||
function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; | ||
// the handle is a net.Socket or net.Server object, or undefined. | ||
function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; | ||
function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; | ||
function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; | ||
function eventNames(): string[]; | ||
const cluster: Cluster; | ||
export default cluster; | ||
} | ||
declare module "node:cluster" { | ||
export * from "cluster"; | ||
export { default as default } from "cluster"; | ||
} |
@@ -0,21 +1,127 @@ | ||
/** | ||
* The `node:console` module provides a simple debugging console that is similar to | ||
* the JavaScript console mechanism provided by web browsers. | ||
* | ||
* 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` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. | ||
* | ||
* _**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` for | ||
* more information. | ||
* | ||
* Example using the global `console`: | ||
* | ||
* ```js | ||
* console.log('hello world'); | ||
* // Prints: hello world, to stdout | ||
* console.log('hello %s', 'world'); | ||
* // Prints: hello world, to stdout | ||
* console.error(new Error('Whoops, something bad happened')); | ||
* // Prints error message and stack trace to stderr: | ||
* // Error: Whoops, something bad happened | ||
* // at [eval]:5:15 | ||
* // at Script.runInThisContext (node:vm:132:18) | ||
* // at Object.runInThisContext (node:vm:309:38) | ||
* // at node:internal/process/execution:77:19 | ||
* // at [eval]-wrapper:6:22 | ||
* // at evalScript (node:internal/process/execution:76:60) | ||
* // at node:internal/main/eval_string:23:3 | ||
* | ||
* const name = 'Will Robinson'; | ||
* console.warn(`Danger ${name}! Danger!`); | ||
* // Prints: Danger Will Robinson! Danger!, to stderr | ||
* ``` | ||
* | ||
* Example using the `Console` class: | ||
* | ||
* ```js | ||
* const out = getStreamSomehow(); | ||
* const err = getStreamSomehow(); | ||
* const myConsole = new console.Console(out, err); | ||
* | ||
* myConsole.log('hello world'); | ||
* // Prints: hello world, to out | ||
* myConsole.log('hello %s', 'world'); | ||
* // Prints: hello world, to out | ||
* myConsole.error(new Error('Whoops, something bad happened')); | ||
* // Prints: [Error: Whoops, something bad happened], to err | ||
* | ||
* const name = 'Will Robinson'; | ||
* myConsole.warn(`Danger ${name}! Danger!`); | ||
* // Prints: Danger Will Robinson! Danger!, to err | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) | ||
*/ | ||
declare module "console" { | ||
import { InspectOptions } from 'util'; | ||
import console = require("node:console"); | ||
export = console; | ||
} | ||
declare module "node:console" { | ||
import { InspectOptions } from "node:util"; | ||
global { | ||
// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build | ||
interface Console { | ||
Console: NodeJS.ConsoleConstructor; | ||
Console: console.ConsoleConstructor; | ||
/** | ||
* A simple assertion test that verifies whether `value` is truthy. | ||
* If it is not, an `AssertionError` is thrown. | ||
* If provided, the error `message` is formatted using `util.format()` and used as the error message. | ||
* `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()`. | ||
* | ||
* If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. | ||
* | ||
* ```js | ||
* console.assert(true, 'does nothing'); | ||
* | ||
* console.assert(false, 'Whoops %s work', 'didn\'t'); | ||
* // Assertion failed: Whoops didn't work | ||
* | ||
* console.assert(); | ||
* // Assertion failed | ||
* ``` | ||
* @since v0.1.101 | ||
* @param value The value tested for being truthy. | ||
* @param message All arguments besides `value` are used as error message. | ||
*/ | ||
assert(value: any, message?: string, ...optionalParams: any[]): void; | ||
/** | ||
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. | ||
* When `stdout` is not a TTY, this method does nothing. | ||
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the | ||
* TTY. When `stdout` is not a TTY, this method does nothing. | ||
* | ||
* The specific operation of `console.clear()` can vary across operating systems | ||
* and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the | ||
* current terminal viewport for the Node.js | ||
* binary. | ||
* @since v8.3.0 | ||
*/ | ||
clear(): void; | ||
/** | ||
* Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. | ||
* Maintains an internal counter specific to `label` and outputs to `stdout` the | ||
* number of times `console.count()` has been called with the given `label`. | ||
* | ||
* ```js | ||
* > console.count() | ||
* default: 1 | ||
* undefined | ||
* > console.count('default') | ||
* default: 2 | ||
* undefined | ||
* > console.count('abc') | ||
* abc: 1 | ||
* undefined | ||
* > console.count('xyz') | ||
* xyz: 1 | ||
* undefined | ||
* > console.count('abc') | ||
* abc: 2 | ||
* undefined | ||
* > console.count() | ||
* default: 3 | ||
* undefined | ||
* > | ||
* ``` | ||
* @since v8.3.0 | ||
* @param [label='default'] The display label for the counter. | ||
*/ | ||
@@ -25,68 +131,190 @@ count(label?: string): void; | ||
* Resets the internal counter specific to `label`. | ||
* | ||
* ```js | ||
* > console.count('abc'); | ||
* abc: 1 | ||
* undefined | ||
* > console.countReset('abc'); | ||
* undefined | ||
* > console.count('abc'); | ||
* abc: 1 | ||
* undefined | ||
* > | ||
* ``` | ||
* @since v8.3.0 | ||
* @param [label='default'] The display label for the counter. | ||
*/ | ||
countReset(label?: string): void; | ||
/** | ||
* The `console.debug()` function is an alias for {@link console.log()}. | ||
* The `console.debug()` function is an alias for {@link log}. | ||
* @since v8.0.0 | ||
*/ | ||
debug(message?: any, ...optionalParams: any[]): void; | ||
/** | ||
* Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. | ||
* Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. | ||
* This function bypasses any custom `inspect()` function defined on `obj`. | ||
* @since v0.1.101 | ||
*/ | ||
dir(obj: any, options?: InspectOptions): void; | ||
/** | ||
* This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting | ||
* This method calls `console.log()` passing it the arguments received. | ||
* This method does not produce any XML formatting. | ||
* @since v8.0.0 | ||
*/ | ||
dirxml(...data: any[]): void; | ||
/** | ||
* Prints to `stderr` with newline. | ||
* 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()`). | ||
* | ||
* ```js | ||
* const code = 5; | ||
* console.error('error #%d', code); | ||
* // Prints: error #5, to stderr | ||
* console.error('error', code); | ||
* // Prints: error 5, to stderr | ||
* ``` | ||
* | ||
* If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string | ||
* values are concatenated. See `util.format()` for more information. | ||
* @since v0.1.100 | ||
*/ | ||
error(message?: any, ...optionalParams: any[]): void; | ||
/** | ||
* Increases indentation of subsequent lines by two spaces. | ||
* If one or more `label`s are provided, those are printed first without the additional indentation. | ||
* Increases indentation of subsequent lines by spaces for `groupIndentation`length. | ||
* | ||
* If one or more `label`s are provided, those are printed first without the | ||
* additional indentation. | ||
* @since v8.5.0 | ||
*/ | ||
group(...label: any[]): void; | ||
/** | ||
* The `console.groupCollapsed()` function is an alias for {@link console.group()}. | ||
* An alias for {@link group}. | ||
* @since v8.5.0 | ||
*/ | ||
groupCollapsed(...label: any[]): void; | ||
/** | ||
* Decreases indentation of subsequent lines by two spaces. | ||
* Decreases indentation of subsequent lines by spaces for `groupIndentation`length. | ||
* @since v8.5.0 | ||
*/ | ||
groupEnd(): void; | ||
/** | ||
* The {@link console.info()} function is an alias for {@link console.log()}. | ||
* The `console.info()` function is an alias for {@link log}. | ||
* @since v0.1.100 | ||
*/ | ||
info(message?: any, ...optionalParams: any[]): void; | ||
/** | ||
* Prints to `stdout` with newline. | ||
* 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()`). | ||
* | ||
* ```js | ||
* const count = 5; | ||
* console.log('count: %d', count); | ||
* // Prints: count: 5, to stdout | ||
* console.log('count:', count); | ||
* // Prints: count: 5, to stdout | ||
* ``` | ||
* | ||
* See `util.format()` for more information. | ||
* @since v0.1.100 | ||
*/ | ||
log(message?: any, ...optionalParams: any[]): void; | ||
/** | ||
* This method does not display anything unless used in the inspector. | ||
* Prints to `stdout` the array `array` formatted as a table. | ||
* Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just | ||
* logging the argument if it can't be parsed as tabular. | ||
* | ||
* ```js | ||
* // These can't be parsed as tabular data | ||
* console.table(Symbol()); | ||
* // Symbol() | ||
* | ||
* console.table(undefined); | ||
* // undefined | ||
* | ||
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); | ||
* // ┌─────────┬─────┬─────┐ | ||
* // │ (index) │ a │ b │ | ||
* // ├─────────┼─────┼─────┤ | ||
* // │ 0 │ 1 │ 'Y' │ | ||
* // │ 1 │ 'Z' │ 2 │ | ||
* // └─────────┴─────┴─────┘ | ||
* | ||
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); | ||
* // ┌─────────┬─────┐ | ||
* // │ (index) │ a │ | ||
* // ├─────────┼─────┤ | ||
* // │ 0 │ 1 │ | ||
* // │ 1 │ 'Z' │ | ||
* // └─────────┴─────┘ | ||
* ``` | ||
* @since v10.0.0 | ||
* @param properties Alternate properties for constructing the table. | ||
*/ | ||
table(tabularData: any, properties?: ReadonlyArray<string>): void; | ||
table(tabularData: any, properties?: readonly string[]): void; | ||
/** | ||
* Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. | ||
* Starts a timer that can be used to compute the duration of an operation. Timers | ||
* are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in | ||
* suitable time units to `stdout`. For example, if the elapsed | ||
* time is 3869ms, `console.timeEnd()` displays "3.869s". | ||
* @since v0.1.104 | ||
* @param [label='default'] | ||
*/ | ||
time(label?: string): void; | ||
/** | ||
* Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. | ||
* Stops a timer that was previously started by calling {@link time} and | ||
* prints the result to `stdout`: | ||
* | ||
* ```js | ||
* console.time('bunch-of-stuff'); | ||
* // Do a bunch of stuff. | ||
* console.timeEnd('bunch-of-stuff'); | ||
* // Prints: bunch-of-stuff: 225.438ms | ||
* ``` | ||
* @since v0.1.104 | ||
* @param [label='default'] | ||
*/ | ||
timeEnd(label?: string): void; | ||
/** | ||
* For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. | ||
* For a timer that was previously started by calling {@link time}, prints | ||
* the elapsed time and other `data` arguments to `stdout`: | ||
* | ||
* ```js | ||
* console.time('process'); | ||
* const value = expensiveProcess1(); // Returns 42 | ||
* console.timeLog('process', value); | ||
* // Prints "process: 365.227ms 42". | ||
* doExpensiveProcess2(value); | ||
* console.timeEnd('process'); | ||
* ``` | ||
* @since v10.7.0 | ||
* @param [label='default'] | ||
*/ | ||
timeLog(label?: string, ...data: any[]): void; | ||
/** | ||
* Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. | ||
* Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. | ||
* | ||
* ```js | ||
* console.trace('Show me'); | ||
* // Prints: (stack trace will vary based on where trace is called) | ||
* // Trace: Show me | ||
* // at repl:2:9 | ||
* // at REPLServer.defaultEval (repl.js:248:27) | ||
* // at bound (domain.js:287:14) | ||
* // at REPLServer.runBound [as eval] (domain.js:300:12) | ||
* // at REPLServer.<anonymous> (repl.js:412:12) | ||
* // at emitOne (events.js:82:20) | ||
* // at REPLServer.emit (events.js:169:7) | ||
* // at REPLServer.Interface._onLine (readline.js:210:10) | ||
* // at REPLServer.Interface._line (readline.js:549:8) | ||
* // at REPLServer.Interface._ttyWrite (readline.js:826:14) | ||
* ``` | ||
* @since v0.1.104 | ||
*/ | ||
trace(message?: any, ...optionalParams: any[]): void; | ||
/** | ||
* The {@link console.warn()} function is an alias for {@link console.error()}. | ||
* The `console.warn()` function is an alias for {@link error}. | ||
* @since v0.1.100 | ||
*/ | ||
warn(message?: any, ...optionalParams: any[]): void; | ||
// --- Inspector mode only --- | ||
@@ -109,27 +337,81 @@ /** | ||
} | ||
var console: Console; | ||
namespace NodeJS { | ||
/** | ||
* The `console` module provides a simple debugging console that is similar to the | ||
* JavaScript console mechanism provided by web browsers. | ||
* | ||
* 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. | ||
* | ||
* _**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` for | ||
* more information. | ||
* | ||
* Example using the global `console`: | ||
* | ||
* ```js | ||
* console.log('hello world'); | ||
* // Prints: hello world, to stdout | ||
* console.log('hello %s', 'world'); | ||
* // Prints: hello world, to stdout | ||
* console.error(new Error('Whoops, something bad happened')); | ||
* // Prints error message and stack trace to stderr: | ||
* // Error: Whoops, something bad happened | ||
* // at [eval]:5:15 | ||
* // at Script.runInThisContext (node:vm:132:18) | ||
* // at Object.runInThisContext (node:vm:309:38) | ||
* // at node:internal/process/execution:77:19 | ||
* // at [eval]-wrapper:6:22 | ||
* // at evalScript (node:internal/process/execution:76:60) | ||
* // at node:internal/main/eval_string:23:3 | ||
* | ||
* const name = 'Will Robinson'; | ||
* console.warn(`Danger ${name}! Danger!`); | ||
* // Prints: Danger Will Robinson! Danger!, to stderr | ||
* ``` | ||
* | ||
* Example using the `Console` class: | ||
* | ||
* ```js | ||
* const out = getStreamSomehow(); | ||
* const err = getStreamSomehow(); | ||
* const myConsole = new console.Console(out, err); | ||
* | ||
* myConsole.log('hello world'); | ||
* // Prints: hello world, to out | ||
* myConsole.log('hello %s', 'world'); | ||
* // Prints: hello world, to out | ||
* myConsole.error(new Error('Whoops, something bad happened')); | ||
* // Prints: [Error: Whoops, something bad happened], to err | ||
* | ||
* const name = 'Will Robinson'; | ||
* myConsole.warn(`Danger ${name}! Danger!`); | ||
* // Prints: Danger Will Robinson! Danger!, to err | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) | ||
*/ | ||
namespace console { | ||
interface ConsoleConstructorOptions { | ||
stdout: WritableStream; | ||
stderr?: WritableStream; | ||
ignoreErrors?: boolean; | ||
colorMode?: boolean | 'auto'; | ||
inspectOptions?: InspectOptions; | ||
stdout: NodeJS.WritableStream; | ||
stderr?: NodeJS.WritableStream | undefined; | ||
ignoreErrors?: boolean | undefined; | ||
colorMode?: boolean | "auto" | undefined; | ||
inspectOptions?: InspectOptions | undefined; | ||
/** | ||
* Set group indentation | ||
* @default 2 | ||
*/ | ||
groupIndentation?: number | undefined; | ||
} | ||
interface ConsoleConstructor { | ||
prototype: Console; | ||
new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; | ||
new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; | ||
new(options: ConsoleConstructorOptions): Console; | ||
} | ||
interface Global { | ||
console: typeof console; | ||
} | ||
} | ||
var console: Console; | ||
} | ||
export = console; | ||
export = globalThis.console; | ||
} |
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ | ||
declare module "constants" { | ||
import { constants as osConstants, SignalConstants } from 'os'; | ||
import { constants as cryptoConstants } from 'crypto'; | ||
import { constants as fsConstants } from 'fs'; | ||
const exp: typeof osConstants.errno & typeof osConstants.priority & SignalConstants & typeof cryptoConstants & typeof fsConstants; | ||
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; | ||
} | ||
declare module "node:constants" { | ||
import constants = require("constants"); | ||
export = constants; | ||
} |
@@ -0,83 +1,525 @@ | ||
/** | ||
* The `node:dgram` module provides an implementation of UDP datagram sockets. | ||
* | ||
* ```js | ||
* import dgram from 'node:dgram'; | ||
* | ||
* const server = dgram.createSocket('udp4'); | ||
* | ||
* server.on('error', (err) => { | ||
* console.error(`server error:\n${err.stack}`); | ||
* server.close(); | ||
* }); | ||
* | ||
* server.on('message', (msg, rinfo) => { | ||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); | ||
* }); | ||
* | ||
* server.on('listening', () => { | ||
* const address = server.address(); | ||
* console.log(`server listening ${address.address}:${address.port}`); | ||
* }); | ||
* | ||
* server.bind(41234); | ||
* // Prints: server listening 0.0.0.0:41234 | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) | ||
*/ | ||
declare module "dgram" { | ||
import { AddressInfo } from "net"; | ||
import * as dns from "dns"; | ||
import * as events from "events"; | ||
import { AddressInfo } from "node:net"; | ||
import * as dns from "node:dns"; | ||
import { Abortable, EventEmitter } from "node:events"; | ||
interface RemoteInfo { | ||
address: string; | ||
family: 'IPv4' | 'IPv6'; | ||
family: "IPv4" | "IPv6"; | ||
port: number; | ||
size: number; | ||
} | ||
interface BindOptions { | ||
port?: number; | ||
address?: string; | ||
exclusive?: boolean; | ||
fd?: number; | ||
port?: number | undefined; | ||
address?: string | undefined; | ||
exclusive?: boolean | undefined; | ||
fd?: number | undefined; | ||
} | ||
type SocketType = "udp4" | "udp6"; | ||
interface SocketOptions { | ||
interface SocketOptions extends Abortable { | ||
type: SocketType; | ||
reuseAddr?: boolean; | ||
reuseAddr?: boolean | undefined; | ||
/** | ||
* @default false | ||
*/ | ||
ipv6Only?: boolean; | ||
recvBufferSize?: number; | ||
sendBufferSize?: number; | ||
lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; | ||
ipv6Only?: boolean | undefined; | ||
recvBufferSize?: number | undefined; | ||
sendBufferSize?: number | undefined; | ||
lookup?: | ||
| (( | ||
hostname: string, | ||
options: dns.LookupOneOptions, | ||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, | ||
) => void) | ||
| undefined; | ||
} | ||
/** | ||
* Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram | ||
* messages. When `address` and `port` are not passed to `socket.bind()` the | ||
* method will bind the socket to the "all interfaces" address on a random port | ||
* (it does the right thing for both `udp4` and `udp6` sockets). The bound address | ||
* and port can be retrieved using `socket.address().address` and `socket.address().port`. | ||
* | ||
* If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: | ||
* | ||
* ```js | ||
* const controller = new AbortController(); | ||
* const { signal } = controller; | ||
* const server = dgram.createSocket({ type: 'udp4', signal }); | ||
* server.on('message', (msg, rinfo) => { | ||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); | ||
* }); | ||
* // Later, when you want to close the server. | ||
* controller.abort(); | ||
* ``` | ||
* @since v0.11.13 | ||
* @param options Available options are: | ||
* @param callback Attached as a listener for `'message'` events. Optional. | ||
*/ | ||
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; | ||
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; | ||
class Socket extends events.EventEmitter { | ||
/** | ||
* Encapsulates the datagram functionality. | ||
* | ||
* New instances of `dgram.Socket` are created using {@link createSocket}. | ||
* The `new` keyword is not to be used to create `dgram.Socket` instances. | ||
* @since v0.1.99 | ||
*/ | ||
class Socket extends EventEmitter { | ||
/** | ||
* Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not | ||
* specified, the operating system will choose | ||
* one interface and will add membership to it. To add membership to every | ||
* available interface, call `addMembership` multiple times, once per interface. | ||
* | ||
* When called on an unbound socket, this method will implicitly bind to a random | ||
* port, listening on all interfaces. | ||
* | ||
* When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: | ||
* | ||
* ```js | ||
* import cluster from 'node:cluster'; | ||
* import dgram from 'node:dgram'; | ||
* | ||
* if (cluster.isPrimary) { | ||
* cluster.fork(); // Works ok. | ||
* cluster.fork(); // Fails with EADDRINUSE. | ||
* } else { | ||
* const s = dgram.createSocket('udp4'); | ||
* s.bind(1234, () => { | ||
* s.addMembership('224.0.0.114'); | ||
* }); | ||
* } | ||
* ``` | ||
* @since v0.6.9 | ||
*/ | ||
addMembership(multicastAddress: string, multicastInterface?: string): void; | ||
/** | ||
* Returns an object containing the address information for a socket. | ||
* For UDP sockets, this object will contain `address`, `family`, and `port`properties. | ||
* | ||
* This method throws `EBADF` if called on an unbound socket. | ||
* @since v0.1.99 | ||
*/ | ||
address(): AddressInfo; | ||
bind(port?: number, address?: string, callback?: () => void): void; | ||
bind(port?: number, callback?: () => void): void; | ||
bind(callback?: () => void): void; | ||
bind(options: BindOptions, callback?: () => void): void; | ||
close(callback?: () => void): void; | ||
/** | ||
* For UDP sockets, causes the `dgram.Socket` to listen for datagram | ||
* messages on a named `port` and optional `address`. If `port` is not | ||
* specified or is `0`, the operating system will attempt to bind to a | ||
* random port. If `address` is not specified, the operating system will | ||
* attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is | ||
* called. | ||
* | ||
* Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very | ||
* useful. | ||
* | ||
* A bound datagram socket keeps the Node.js process running to receive | ||
* datagram messages. | ||
* | ||
* If binding fails, an `'error'` event is generated. In rare case (e.g. | ||
* attempting to bind with a closed socket), an `Error` may be thrown. | ||
* | ||
* Example of a UDP server listening on port 41234: | ||
* | ||
* ```js | ||
* import dgram from 'node:dgram'; | ||
* | ||
* const server = dgram.createSocket('udp4'); | ||
* | ||
* server.on('error', (err) => { | ||
* console.error(`server error:\n${err.stack}`); | ||
* server.close(); | ||
* }); | ||
* | ||
* server.on('message', (msg, rinfo) => { | ||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); | ||
* }); | ||
* | ||
* server.on('listening', () => { | ||
* const address = server.address(); | ||
* console.log(`server listening ${address.address}:${address.port}`); | ||
* }); | ||
* | ||
* server.bind(41234); | ||
* // Prints: server listening 0.0.0.0:41234 | ||
* ``` | ||
* @since v0.1.99 | ||
* @param callback with no parameters. Called when binding is complete. | ||
*/ | ||
bind(port?: number, address?: string, callback?: () => void): this; | ||
bind(port?: number, callback?: () => void): this; | ||
bind(callback?: () => void): this; | ||
bind(options: BindOptions, callback?: () => void): this; | ||
/** | ||
* Close the underlying socket and stop listening for data on it. If a callback is | ||
* provided, it is added as a listener for the `'close'` event. | ||
* @since v0.1.99 | ||
* @param callback Called when the socket has been closed. | ||
*/ | ||
close(callback?: () => void): this; | ||
/** | ||
* Associates the `dgram.Socket` to a remote address and port. Every | ||
* message sent by this handle is automatically sent to that destination. Also, | ||
* the socket will only receive messages from that remote peer. | ||
* Trying to call `connect()` on an already connected socket will result | ||
* in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not | ||
* provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) | ||
* will be used by default. Once the connection is complete, a `'connect'` event | ||
* is emitted and the optional `callback` function is called. In case of failure, | ||
* the `callback` is called or, failing this, an `'error'` event is emitted. | ||
* @since v12.0.0 | ||
* @param callback Called when the connection is completed or on error. | ||
*/ | ||
connect(port: number, address?: string, callback?: () => void): void; | ||
connect(port: number, callback: () => void): void; | ||
/** | ||
* A synchronous function that disassociates a connected `dgram.Socket` from | ||
* its remote address. Trying to call `disconnect()` on an unbound or already | ||
* disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. | ||
* @since v12.0.0 | ||
*/ | ||
disconnect(): void; | ||
/** | ||
* Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the | ||
* kernel when the socket is closed or the process terminates, so most apps will | ||
* never have reason to call this. | ||
* | ||
* If `multicastInterface` is not specified, the operating system will attempt to | ||
* drop membership on all valid interfaces. | ||
* @since v0.6.9 | ||
*/ | ||
dropMembership(multicastAddress: string, multicastInterface?: string): void; | ||
/** | ||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. | ||
* @since v8.7.0 | ||
* @return the `SO_RCVBUF` socket receive buffer size in bytes. | ||
*/ | ||
getRecvBufferSize(): number; | ||
/** | ||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. | ||
* @since v8.7.0 | ||
* @return the `SO_SNDBUF` socket send buffer size in bytes. | ||
*/ | ||
getSendBufferSize(): number; | ||
/** | ||
* By default, binding a socket will cause it to block the Node.js process from | ||
* exiting as long as the socket is open. The `socket.unref()` method can be used | ||
* to exclude the socket from the reference counting that keeps the Node.js | ||
* process active. The `socket.ref()` method adds the socket back to the reference | ||
* counting and restores the default behavior. | ||
* | ||
* Calling `socket.ref()` multiples times will have no additional effect. | ||
* | ||
* The `socket.ref()` method returns a reference to the socket so calls can be | ||
* chained. | ||
* @since v0.9.1 | ||
*/ | ||
ref(): this; | ||
/** | ||
* Returns an object containing the `address`, `family`, and `port` of the remote | ||
* endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception | ||
* if the socket is not connected. | ||
* @since v12.0.0 | ||
*/ | ||
remoteAddress(): AddressInfo; | ||
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; | ||
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, callback?: (error: Error | null, bytes: number) => void): void; | ||
send(msg: string | Uint8Array | ReadonlyArray<any>, callback?: (error: Error | null, bytes: number) => void): void; | ||
send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; | ||
send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; | ||
send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; | ||
/** | ||
* Broadcasts a datagram on the socket. | ||
* For connectionless sockets, the destination `port` and `address` must be | ||
* specified. Connected sockets, on the other hand, will use their associated | ||
* remote endpoint, so the `port` and `address` arguments must not be set. | ||
* | ||
* The `msg` argument contains the message to be sent. | ||
* Depending on its type, different behavior can apply. If `msg` is a `Buffer`, | ||
* any `TypedArray` or a `DataView`, | ||
* the `offset` and `length` specify the offset within the `Buffer` where the | ||
* message begins and the number of bytes in the message, respectively. | ||
* If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that | ||
* contain multi-byte characters, `offset` and `length` will be calculated with | ||
* respect to `byte length` and not the character position. | ||
* If `msg` is an array, `offset` and `length` must not be specified. | ||
* | ||
* The `address` argument is a string. If the value of `address` is a host name, | ||
* DNS will be used to resolve the address of the host. If `address` is not | ||
* provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. | ||
* | ||
* If the socket has not been previously bound with a call to `bind`, the socket | ||
* is assigned a random port number and is bound to the "all interfaces" address | ||
* (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) | ||
* | ||
* An optional `callback` function may be specified to as a way of reporting | ||
* DNS errors or for determining when it is safe to reuse the `buf` object. | ||
* DNS lookups delay the time to send for at least one tick of the | ||
* Node.js event loop. | ||
* | ||
* The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be | ||
* passed as the first argument to the `callback`. If a `callback` is not given, | ||
* the error is emitted as an `'error'` event on the `socket` object. | ||
* | ||
* Offset and length are optional but both _must_ be set if either are used. | ||
* They are supported only when the first argument is a `Buffer`, a `TypedArray`, | ||
* or a `DataView`. | ||
* | ||
* This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. | ||
* | ||
* Example of sending a UDP packet to a port on `localhost`; | ||
* | ||
* ```js | ||
* import dgram from 'node:dgram'; | ||
* import { Buffer } from 'node:buffer'; | ||
* | ||
* const message = Buffer.from('Some bytes'); | ||
* const client = dgram.createSocket('udp4'); | ||
* client.send(message, 41234, 'localhost', (err) => { | ||
* client.close(); | ||
* }); | ||
* ``` | ||
* | ||
* Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; | ||
* | ||
* ```js | ||
* import dgram from 'node:dgram'; | ||
* import { Buffer } from 'node:buffer'; | ||
* | ||
* const buf1 = Buffer.from('Some '); | ||
* const buf2 = Buffer.from('bytes'); | ||
* const client = dgram.createSocket('udp4'); | ||
* client.send([buf1, buf2], 41234, (err) => { | ||
* client.close(); | ||
* }); | ||
* ``` | ||
* | ||
* Sending multiple buffers might be faster or slower depending on the | ||
* application and operating system. Run benchmarks to | ||
* determine the optimal strategy on a case-by-case basis. Generally speaking, | ||
* however, sending multiple buffers is faster. | ||
* | ||
* Example of sending a UDP packet using a socket connected to a port on`localhost`: | ||
* | ||
* ```js | ||
* import dgram from 'node:dgram'; | ||
* import { Buffer } from 'node:buffer'; | ||
* | ||
* const message = Buffer.from('Some bytes'); | ||
* const client = dgram.createSocket('udp4'); | ||
* client.connect(41234, 'localhost', (err) => { | ||
* client.send(message, (err) => { | ||
* client.close(); | ||
* }); | ||
* }); | ||
* ``` | ||
* @since v0.1.99 | ||
* @param msg Message to be sent. | ||
* @param offset Offset in the buffer where the message starts. | ||
* @param length Number of bytes in the message. | ||
* @param port Destination port. | ||
* @param address Destination host name or IP address. | ||
* @param callback Called when the message has been sent. | ||
*/ | ||
send( | ||
msg: string | Uint8Array | readonly any[], | ||
port?: number, | ||
address?: string, | ||
callback?: (error: Error | null, bytes: number) => void, | ||
): void; | ||
send( | ||
msg: string | Uint8Array | readonly any[], | ||
port?: number, | ||
callback?: (error: Error | null, bytes: number) => void, | ||
): void; | ||
send( | ||
msg: string | Uint8Array | readonly any[], | ||
callback?: (error: Error | null, bytes: number) => void, | ||
): void; | ||
send( | ||
msg: string | Uint8Array, | ||
offset: number, | ||
length: number, | ||
port?: number, | ||
address?: string, | ||
callback?: (error: Error | null, bytes: number) => void, | ||
): void; | ||
send( | ||
msg: string | Uint8Array, | ||
offset: number, | ||
length: number, | ||
port?: number, | ||
callback?: (error: Error | null, bytes: number) => void, | ||
): void; | ||
send( | ||
msg: string | Uint8Array, | ||
offset: number, | ||
length: number, | ||
callback?: (error: Error | null, bytes: number) => void, | ||
): void; | ||
/** | ||
* Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP | ||
* packets may be sent to a local interface's broadcast address. | ||
* | ||
* This method throws `EBADF` if called on an unbound socket. | ||
* @since v0.6.9 | ||
*/ | ||
setBroadcast(flag: boolean): void; | ||
/** | ||
* _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC | ||
* 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ | ||
* _with a scope index is written as `'IP%scope'` where scope is an interface name_ | ||
* _or interface number._ | ||
* | ||
* Sets the default outgoing multicast interface of the socket to a chosen | ||
* interface or back to system interface selection. The `multicastInterface` must | ||
* be a valid string representation of an IP from the socket's family. | ||
* | ||
* For IPv4 sockets, this should be the IP configured for the desired physical | ||
* interface. All packets sent to multicast on the socket will be sent on the | ||
* interface determined by the most recent successful use of this call. | ||
* | ||
* For IPv6 sockets, `multicastInterface` should include a scope to indicate the | ||
* interface as in the examples that follow. In IPv6, individual `send` calls can | ||
* also use explicit scope in addresses, so only packets sent to a multicast | ||
* address without specifying an explicit scope are affected by the most recent | ||
* successful use of this call. | ||
* | ||
* This method throws `EBADF` if called on an unbound socket. | ||
* | ||
* #### Example: IPv6 outgoing multicast interface | ||
* | ||
* On most systems, where scope format uses the interface name: | ||
* | ||
* ```js | ||
* const socket = dgram.createSocket('udp6'); | ||
* | ||
* socket.bind(1234, () => { | ||
* socket.setMulticastInterface('::%eth1'); | ||
* }); | ||
* ``` | ||
* | ||
* On Windows, where scope format uses an interface number: | ||
* | ||
* ```js | ||
* const socket = dgram.createSocket('udp6'); | ||
* | ||
* socket.bind(1234, () => { | ||
* socket.setMulticastInterface('::%2'); | ||
* }); | ||
* ``` | ||
* | ||
* #### Example: IPv4 outgoing multicast interface | ||
* | ||
* All systems use an IP of the host on the desired physical interface: | ||
* | ||
* ```js | ||
* const socket = dgram.createSocket('udp4'); | ||
* | ||
* socket.bind(1234, () => { | ||
* socket.setMulticastInterface('10.0.0.2'); | ||
* }); | ||
* ``` | ||
* @since v8.6.0 | ||
*/ | ||
setMulticastInterface(multicastInterface: string): void; | ||
setMulticastLoopback(flag: boolean): void; | ||
setMulticastTTL(ttl: number): void; | ||
/** | ||
* Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, | ||
* multicast packets will also be received on the local interface. | ||
* | ||
* This method throws `EBADF` if called on an unbound socket. | ||
* @since v0.3.8 | ||
*/ | ||
setMulticastLoopback(flag: boolean): boolean; | ||
/** | ||
* Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for | ||
* "Time to Live", in this context it specifies the number of IP hops that a | ||
* packet is allowed to travel through, specifically for multicast traffic. Each | ||
* router or gateway that forwards a packet decrements the TTL. If the TTL is | ||
* decremented to 0 by a router, it will not be forwarded. | ||
* | ||
* The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. | ||
* | ||
* This method throws `EBADF` if called on an unbound socket. | ||
* @since v0.3.8 | ||
*/ | ||
setMulticastTTL(ttl: number): number; | ||
/** | ||
* Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer | ||
* in bytes. | ||
* | ||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. | ||
* @since v8.7.0 | ||
*/ | ||
setRecvBufferSize(size: number): void; | ||
/** | ||
* Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer | ||
* in bytes. | ||
* | ||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. | ||
* @since v8.7.0 | ||
*/ | ||
setSendBufferSize(size: number): void; | ||
setTTL(ttl: number): void; | ||
/** | ||
* Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", | ||
* in this context it specifies the number of IP hops that a packet is allowed to | ||
* travel through. Each router or gateway that forwards a packet decrements the | ||
* TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. | ||
* Changing TTL values is typically done for network probes or when multicasting. | ||
* | ||
* The `ttl` argument may be between 1 and 255\. The default on most systems | ||
* is 64. | ||
* | ||
* This method throws `EBADF` if called on an unbound socket. | ||
* @since v0.1.101 | ||
*/ | ||
setTTL(ttl: number): number; | ||
/** | ||
* By default, binding a socket will cause it to block the Node.js process from | ||
* exiting as long as the socket is open. The `socket.unref()` method can be used | ||
* to exclude the socket from the reference counting that keeps the Node.js | ||
* process active, allowing the process to exit even if the socket is still | ||
* listening. | ||
* | ||
* Calling `socket.unref()` multiple times will have no addition effect. | ||
* | ||
* The `socket.unref()` method returns a reference to the socket so calls can be | ||
* chained. | ||
* @since v0.9.1 | ||
*/ | ||
unref(): this; | ||
/** | ||
* Tells the kernel to join a source-specific multicast channel at the given | ||
* `sourceAddress` and `groupAddress`, using the `multicastInterface` with the | ||
* `IP_ADD_SOURCE_MEMBERSHIP` socket option. | ||
* If the `multicastInterface` argument | ||
* Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket | ||
* option. If the `multicastInterface` argument | ||
* is not specified, the operating system will choose one interface and will add | ||
* membership to it. | ||
* To add membership to every available interface, call | ||
* `socket.addSourceSpecificMembership()` multiple times, once per interface. | ||
* membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. | ||
* | ||
* When called on an unbound socket, this method will implicitly bind to a random | ||
* port, listening on all interfaces. | ||
* @since v13.1.0, v12.16.0 | ||
*/ | ||
addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; | ||
/** | ||
* Instructs the kernel to leave a source-specific multicast channel at the given | ||
* `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` | ||
* socket option. This method is automatically called by the kernel when the | ||
* Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is | ||
* automatically called by the kernel when the | ||
* socket is closed or the process terminates, so most apps will never have | ||
@@ -88,5 +530,5 @@ * reason to call this. | ||
* drop membership on all valid interfaces. | ||
* @since v13.1.0, v12.16.0 | ||
*/ | ||
dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; | ||
/** | ||
@@ -106,3 +548,2 @@ * events.EventEmitter | ||
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -114,3 +555,2 @@ emit(event: "close"): boolean; | ||
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -122,3 +562,2 @@ on(event: "close", listener: () => void): this; | ||
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -130,3 +569,2 @@ once(event: "close", listener: () => void): this; | ||
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -138,3 +576,2 @@ prependListener(event: "close", listener: () => void): this; | ||
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -146,3 +583,11 @@ prependOnceListener(event: "close", listener: () => void): this; | ||
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; | ||
/** | ||
* Calls `socket.close()` and returns a promise that fulfills when the socket has closed. | ||
* @since v20.5.0 | ||
*/ | ||
[Symbol.asyncDispose](): Promise<void>; | ||
} | ||
} | ||
declare module "node:dgram" { | ||
export * from "dgram"; | ||
} |
@@ -0,5 +1,52 @@ | ||
/** | ||
* The `node:dns` module enables name resolution. For example, use it to look up IP | ||
* addresses of host names. | ||
* | ||
* Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the | ||
* DNS protocol for lookups. {@link lookup} uses the operating system | ||
* facilities to perform name resolution. It may not need to perform any network | ||
* communication. To perform name resolution the way other applications on the same | ||
* system do, use {@link lookup}. | ||
* | ||
* ```js | ||
* const dns = require('node:dns'); | ||
* | ||
* dns.lookup('example.org', (err, address, family) => { | ||
* console.log('address: %j family: IPv%s', address, family); | ||
* }); | ||
* // address: "93.184.216.34" family: IPv4 | ||
* ``` | ||
* | ||
* All other functions in the `node:dns` module connect to an actual DNS server to | ||
* perform name resolution. They will always use the network to perform DNS | ||
* queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform | ||
* DNS queries, bypassing other name-resolution facilities. | ||
* | ||
* ```js | ||
* const dns = require('node:dns'); | ||
* | ||
* dns.resolve4('archive.org', (err, addresses) => { | ||
* if (err) throw err; | ||
* | ||
* console.log(`addresses: ${JSON.stringify(addresses)}`); | ||
* | ||
* addresses.forEach((a) => { | ||
* dns.reverse(a, (err, hostnames) => { | ||
* if (err) { | ||
* throw err; | ||
* } | ||
* console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); | ||
* }); | ||
* }); | ||
* }); | ||
* ``` | ||
* | ||
* See the `Implementation considerations section` for more information. | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) | ||
*/ | ||
declare module "dns" { | ||
import * as dnsPromises from "node:dns/promises"; | ||
// Supported getaddrinfo flags. | ||
const ADDRCONFIG: number; | ||
const V4MAPPED: number; | ||
export const ADDRCONFIG: number; | ||
export const V4MAPPED: number; | ||
/** | ||
@@ -9,32 +56,89 @@ * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as | ||
*/ | ||
const ALL: number; | ||
interface LookupOptions { | ||
family?: number; | ||
hints?: number; | ||
all?: boolean; | ||
verbatim?: boolean; | ||
export const ALL: number; | ||
export interface LookupOptions { | ||
family?: number | undefined; | ||
hints?: number | undefined; | ||
all?: boolean | undefined; | ||
/** | ||
* @default true | ||
*/ | ||
verbatim?: boolean | undefined; | ||
} | ||
interface LookupOneOptions extends LookupOptions { | ||
all?: false; | ||
export interface LookupOneOptions extends LookupOptions { | ||
all?: false | undefined; | ||
} | ||
interface LookupAllOptions extends LookupOptions { | ||
export interface LookupAllOptions extends LookupOptions { | ||
all: true; | ||
} | ||
interface LookupAddress { | ||
export interface LookupAddress { | ||
address: string; | ||
family: number; | ||
} | ||
function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; | ||
function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; | ||
function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; | ||
function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; | ||
function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; | ||
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. | ||
namespace lookup { | ||
/** | ||
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or | ||
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an | ||
* integer, then it must be `4` or `6` – if `options` is `0` or not provided, then | ||
* IPv4 and IPv6 addresses are both returned if found. | ||
* | ||
* With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the | ||
* properties `address` and `family`. | ||
* | ||
* On error, `err` is an `Error` object, where `err.code` is the error code. | ||
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when | ||
* the host name does not exist but also when the lookup fails in other ways | ||
* such as no available file descriptors. | ||
* | ||
* `dns.lookup()` does not necessarily have anything to do with the DNS protocol. | ||
* 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` before using`dns.lookup()`. | ||
* | ||
* Example usage: | ||
* | ||
* ```js | ||
* const dns = require('node:dns'); | ||
* const options = { | ||
* family: 6, | ||
* hints: dns.ADDRCONFIG | dns.V4MAPPED, | ||
* }; | ||
* dns.lookup('example.com', options, (err, address, family) => | ||
* console.log('address: %j family: IPv%s', address, family)); | ||
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 | ||
* | ||
* // When options.all is true, the result will be an Array. | ||
* options.all = true; | ||
* dns.lookup('example.com', options, (err, addresses) => | ||
* console.log('addresses: %j', addresses)); | ||
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] | ||
* ``` | ||
* | ||
* If this method is invoked as its `util.promisify()` 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 | ||
*/ | ||
export function lookup( | ||
hostname: string, | ||
family: number, | ||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, | ||
): void; | ||
export function lookup( | ||
hostname: string, | ||
options: LookupOneOptions, | ||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, | ||
): void; | ||
export function lookup( | ||
hostname: string, | ||
options: LookupAllOptions, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, | ||
): void; | ||
export function lookup( | ||
hostname: string, | ||
options: LookupOptions, | ||
callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, | ||
): void; | ||
export function lookup( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, | ||
): void; | ||
export namespace lookup { | ||
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>; | ||
@@ -44,43 +148,70 @@ function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>; | ||
} | ||
function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; | ||
namespace lookupService { | ||
function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; | ||
/** | ||
* Resolves the given `address` and `port` into a host name and service using | ||
* the operating system's underlying `getnameinfo` implementation. | ||
* | ||
* 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` object, where `err.code` is the error code. | ||
* | ||
* ```js | ||
* const dns = require('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()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. | ||
* @since v0.11.14 | ||
*/ | ||
export function lookupService( | ||
address: string, | ||
port: number, | ||
callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, | ||
): void; | ||
export namespace lookupService { | ||
function __promisify__( | ||
address: string, | ||
port: number, | ||
): Promise<{ | ||
hostname: string; | ||
service: string; | ||
}>; | ||
} | ||
interface ResolveOptions { | ||
export interface ResolveOptions { | ||
ttl: boolean; | ||
} | ||
interface ResolveWithTtlOptions extends ResolveOptions { | ||
export interface ResolveWithTtlOptions extends ResolveOptions { | ||
ttl: true; | ||
} | ||
interface RecordWithTtl { | ||
export interface RecordWithTtl { | ||
address: string; | ||
ttl: number; | ||
} | ||
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ | ||
type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; | ||
interface AnyARecord extends RecordWithTtl { | ||
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; | ||
export interface AnyARecord extends RecordWithTtl { | ||
type: "A"; | ||
} | ||
interface AnyAaaaRecord extends RecordWithTtl { | ||
export interface AnyAaaaRecord extends RecordWithTtl { | ||
type: "AAAA"; | ||
} | ||
interface MxRecord { | ||
export interface CaaRecord { | ||
critical: number; | ||
issue?: string | undefined; | ||
issuewild?: string | undefined; | ||
iodef?: string | undefined; | ||
contactemail?: string | undefined; | ||
contactphone?: string | undefined; | ||
} | ||
export interface MxRecord { | ||
priority: number; | ||
exchange: string; | ||
} | ||
interface AnyMxRecord extends MxRecord { | ||
export interface AnyMxRecord extends MxRecord { | ||
type: "MX"; | ||
} | ||
interface NaptrRecord { | ||
export interface NaptrRecord { | ||
flags: string; | ||
@@ -93,8 +224,6 @@ service: string; | ||
} | ||
interface AnyNaptrRecord extends NaptrRecord { | ||
export interface AnyNaptrRecord extends NaptrRecord { | ||
type: "NAPTR"; | ||
} | ||
interface SoaRecord { | ||
export interface SoaRecord { | ||
nsname: string; | ||
@@ -108,8 +237,6 @@ hostmaster: string; | ||
} | ||
interface AnySoaRecord extends SoaRecord { | ||
export interface AnySoaRecord extends SoaRecord { | ||
type: "SOA"; | ||
} | ||
interface SrvRecord { | ||
export interface SrvRecord { | ||
priority: number; | ||
@@ -120,58 +247,112 @@ weight: number; | ||
} | ||
interface AnySrvRecord extends SrvRecord { | ||
export interface AnySrvRecord extends SrvRecord { | ||
type: "SRV"; | ||
} | ||
interface AnyTxtRecord { | ||
export interface AnyTxtRecord { | ||
type: "TXT"; | ||
entries: string[]; | ||
} | ||
interface AnyNsRecord { | ||
export interface AnyNsRecord { | ||
type: "NS"; | ||
value: string; | ||
} | ||
interface AnyPtrRecord { | ||
export interface AnyPtrRecord { | ||
type: "PTR"; | ||
value: string; | ||
} | ||
interface AnyCnameRecord { | ||
export interface AnyCnameRecord { | ||
type: "CNAME"; | ||
value: string; | ||
} | ||
type AnyRecord = AnyARecord | | ||
AnyAaaaRecord | | ||
AnyCnameRecord | | ||
AnyMxRecord | | ||
AnyNaptrRecord | | ||
AnyNsRecord | | ||
AnyPtrRecord | | ||
AnySoaRecord | | ||
AnySrvRecord | | ||
AnyTxtRecord; | ||
function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; | ||
function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; | ||
function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; | ||
function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; | ||
function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; | ||
function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; | ||
function resolve( | ||
export type AnyRecord = | ||
| AnyARecord | ||
| AnyAaaaRecord | ||
| AnyCnameRecord | ||
| AnyMxRecord | ||
| AnyNaptrRecord | ||
| AnyNsRecord | ||
| AnyPtrRecord | ||
| AnySoaRecord | ||
| AnySrvRecord | ||
| AnyTxtRecord; | ||
/** | ||
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array | ||
* of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource | ||
* records. The type and structure of individual results varies based on `rrtype`: | ||
* | ||
* <omitted> | ||
* | ||
* On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. | ||
* @since v0.1.27 | ||
* @param hostname Host name to resolve. | ||
* @param [rrtype='A'] Resource record type. | ||
*/ | ||
export function resolve( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "A", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "AAAA", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "ANY", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "CNAME", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "MX", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "NAPTR", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "NS", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "PTR", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "SOA", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "SRV", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: "TXT", | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, | ||
): void; | ||
export function resolve( | ||
hostname: string, | ||
rrtype: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, | ||
callback: ( | ||
err: NodeJS.ErrnoException | null, | ||
addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], | ||
) => void, | ||
): void; | ||
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. | ||
namespace resolve { | ||
export namespace resolve { | ||
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>; | ||
@@ -184,11 +365,28 @@ function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; | ||
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>; | ||
function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; | ||
function __promisify__( | ||
hostname: string, | ||
rrtype: string, | ||
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; | ||
} | ||
function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; | ||
function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; | ||
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. | ||
namespace resolve4 { | ||
/** | ||
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function | ||
* will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). | ||
* @since v0.1.16 | ||
* @param hostname Host name to resolve. | ||
*/ | ||
export function resolve4( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve4( | ||
hostname: string, | ||
options: ResolveWithTtlOptions, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, | ||
): void; | ||
export function resolve4( | ||
hostname: string, | ||
options: ResolveOptions, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, | ||
): void; | ||
export namespace resolve4 { | ||
function __promisify__(hostname: string): Promise<string[]>; | ||
@@ -198,9 +396,23 @@ function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; | ||
} | ||
function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; | ||
function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; | ||
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. | ||
namespace resolve6 { | ||
/** | ||
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function | ||
* will contain an array of IPv6 addresses. | ||
* @since v0.1.16 | ||
* @param hostname Host name to resolve. | ||
*/ | ||
export function resolve6( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export function resolve6( | ||
hostname: string, | ||
options: ResolveWithTtlOptions, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, | ||
): void; | ||
export function resolve6( | ||
hostname: string, | ||
options: ResolveOptions, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, | ||
): void; | ||
export namespace resolve6 { | ||
function __promisify__(hostname: string): Promise<string[]>; | ||
@@ -210,79 +422,358 @@ function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; | ||
} | ||
function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
namespace resolveCname { | ||
/** | ||
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function | ||
* will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). | ||
* @since v0.3.2 | ||
*/ | ||
export function resolveCname( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export namespace resolveCname { | ||
function __promisify__(hostname: string): Promise<string[]>; | ||
} | ||
function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; | ||
namespace resolveMx { | ||
/** | ||
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function | ||
* will contain an array of certification authority authorization records | ||
* available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). | ||
* @since v15.0.0, v14.17.0 | ||
*/ | ||
export function resolveCaa( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, | ||
): void; | ||
export namespace resolveCaa { | ||
function __promisify__(hostname: string): Promise<CaaRecord[]>; | ||
} | ||
/** | ||
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will | ||
* contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). | ||
* @since v0.1.27 | ||
*/ | ||
export function resolveMx( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, | ||
): void; | ||
export namespace resolveMx { | ||
function __promisify__(hostname: string): Promise<MxRecord[]>; | ||
} | ||
function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; | ||
namespace resolveNaptr { | ||
/** | ||
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of | ||
* objects with the following properties: | ||
* | ||
* * `flags` | ||
* * `service` | ||
* * `regexp` | ||
* * `replacement` | ||
* * `order` | ||
* * `preference` | ||
* | ||
* ```js | ||
* { | ||
* flags: 's', | ||
* service: 'SIP+D2U', | ||
* regexp: '', | ||
* replacement: '_sip._udp.example.com', | ||
* order: 30, | ||
* preference: 100 | ||
* } | ||
* ``` | ||
* @since v0.9.12 | ||
*/ | ||
export function resolveNaptr( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, | ||
): void; | ||
export namespace resolveNaptr { | ||
function __promisify__(hostname: string): Promise<NaptrRecord[]>; | ||
} | ||
function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
namespace resolveNs { | ||
/** | ||
* Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will | ||
* contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). | ||
* @since v0.1.90 | ||
*/ | ||
export function resolveNs( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export namespace resolveNs { | ||
function __promisify__(hostname: string): Promise<string[]>; | ||
} | ||
function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; | ||
namespace resolvePtr { | ||
/** | ||
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will | ||
* be an array of strings containing the reply records. | ||
* @since v6.0.0 | ||
*/ | ||
export function resolvePtr( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, | ||
): void; | ||
export namespace resolvePtr { | ||
function __promisify__(hostname: string): Promise<string[]>; | ||
} | ||
function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; | ||
namespace resolveSoa { | ||
/** | ||
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for | ||
* the `hostname`. The `address` argument passed to the `callback` function will | ||
* be an object with the following properties: | ||
* | ||
* * `nsname` | ||
* * `hostmaster` | ||
* * `serial` | ||
* * `refresh` | ||
* * `retry` | ||
* * `expire` | ||
* * `minttl` | ||
* | ||
* ```js | ||
* { | ||
* nsname: 'ns.example.com', | ||
* hostmaster: 'root.example.com', | ||
* serial: 2013101809, | ||
* refresh: 10000, | ||
* retry: 2400, | ||
* expire: 604800, | ||
* minttl: 3600 | ||
* } | ||
* ``` | ||
* @since v0.11.10 | ||
*/ | ||
export function resolveSoa( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, | ||
): void; | ||
export namespace resolveSoa { | ||
function __promisify__(hostname: string): Promise<SoaRecord>; | ||
} | ||
function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; | ||
namespace resolveSrv { | ||
/** | ||
* Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will | ||
* be an array of objects with the following properties: | ||
* | ||
* * `priority` | ||
* * `weight` | ||
* * `port` | ||
* * `name` | ||
* | ||
* ```js | ||
* { | ||
* priority: 10, | ||
* weight: 5, | ||
* port: 21223, | ||
* name: 'service.example.com' | ||
* } | ||
* ``` | ||
* @since v0.1.27 | ||
*/ | ||
export function resolveSrv( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, | ||
): void; | ||
export namespace resolveSrv { | ||
function __promisify__(hostname: string): Promise<SrvRecord[]>; | ||
} | ||
function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; | ||
namespace resolveTxt { | ||
/** | ||
* 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 | ||
* one record. Depending on the use case, these could be either joined together or | ||
* treated separately. | ||
* @since v0.1.27 | ||
*/ | ||
export function resolveTxt( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, | ||
): void; | ||
export namespace resolveTxt { | ||
function __promisify__(hostname: string): Promise<string[][]>; | ||
} | ||
function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; | ||
namespace resolveAny { | ||
/** | ||
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). | ||
* The `ret` argument passed to the `callback` function will be an array containing | ||
* various types of records. Each object has a property `type` that indicates the | ||
* type of the current record. And depending on the `type`, additional properties | ||
* will be present on the object: | ||
* | ||
* <omitted> | ||
* | ||
* Here is an example of the `ret` object passed to the callback: | ||
* | ||
* ```js | ||
* [ { type: 'A', address: '127.0.0.1', ttl: 299 }, | ||
* { type: 'CNAME', value: 'example.com' }, | ||
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, | ||
* { type: 'NS', value: 'ns1.example.com' }, | ||
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, | ||
* { type: 'SOA', | ||
* nsname: 'ns1.example.com', | ||
* hostmaster: 'admin.example.com', | ||
* serial: 156696742, | ||
* refresh: 900, | ||
* retry: 900, | ||
* expire: 1800, | ||
* minttl: 60 } ] | ||
* ``` | ||
* | ||
* DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC | ||
* 8482](https://tools.ietf.org/html/rfc8482). | ||
*/ | ||
export function resolveAny( | ||
hostname: string, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, | ||
): void; | ||
export namespace resolveAny { | ||
function __promisify__(hostname: string): Promise<AnyRecord[]>; | ||
} | ||
function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; | ||
function setServers(servers: ReadonlyArray<string>): void; | ||
function getServers(): string[]; | ||
/** | ||
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an | ||
* array of host names. | ||
* | ||
* On error, `err` is an `Error` object, where `err.code` is | ||
* one of the `DNS error codes`. | ||
* @since v0.1.16 | ||
*/ | ||
export function reverse( | ||
ip: string, | ||
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, | ||
): void; | ||
/** | ||
* Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: | ||
* | ||
* * `ipv4first`: for `verbatim` defaulting to `false`. | ||
* * `verbatim`: for `verbatim` defaulting to `true`. | ||
* @since v20.1.0 | ||
*/ | ||
export function getDefaultResultOrder(): "ipv4first" | "verbatim"; | ||
/** | ||
* Sets the IP address and port of servers to be used when performing DNS | ||
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted | ||
* addresses. If the port is the IANA default DNS port (53) it can be omitted. | ||
* | ||
* ```js | ||
* dns.setServers([ | ||
* '4.4.4.4', | ||
* '[2001:4860:4860::8888]', | ||
* '4.4.4.4:1053', | ||
* '[2001:4860:4860::8888]:1053', | ||
* ]); | ||
* ``` | ||
* | ||
* An error will be thrown if an invalid address is provided. | ||
* | ||
* The `dns.setServers()` method must not be called while a DNS query is in | ||
* progress. | ||
* | ||
* The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). | ||
* | ||
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). | ||
* That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with | ||
* subsequent servers provided. Fallback DNS servers will only be used if the | ||
* earlier ones time out or result in some other error. | ||
* @since v0.11.3 | ||
* @param servers array of `RFC 5952` formatted addresses | ||
*/ | ||
export function setServers(servers: readonly string[]): void; | ||
/** | ||
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), | ||
* that are currently configured for DNS resolution. A string will include a port | ||
* section if a custom port is used. | ||
* | ||
* ```js | ||
* [ | ||
* '4.4.4.4', | ||
* '2001:4860:4860::8888', | ||
* '4.4.4.4:1053', | ||
* '[2001:4860:4860::8888]:1053', | ||
* ] | ||
* ``` | ||
* @since v0.11.3 | ||
*/ | ||
export function getServers(): string[]; | ||
/** | ||
* Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: | ||
* | ||
* * `ipv4first`: sets default `verbatim` `false`. | ||
* * `verbatim`: sets default `verbatim` `true`. | ||
* | ||
* The default is `verbatim` and {@link setDefaultResultOrder} have higher | ||
* priority than `--dns-result-order`. When using `worker threads`,{@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'` or `'verbatim'`. | ||
*/ | ||
export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; | ||
// Error codes | ||
const NODATA: string; | ||
const FORMERR: string; | ||
const SERVFAIL: string; | ||
const NOTFOUND: string; | ||
const NOTIMP: string; | ||
const REFUSED: string; | ||
const BADQUERY: string; | ||
const BADNAME: string; | ||
const BADFAMILY: string; | ||
const BADRESP: string; | ||
const CONNREFUSED: string; | ||
const TIMEOUT: string; | ||
const EOF: string; | ||
const FILE: string; | ||
const NOMEM: string; | ||
const DESTRUCTION: string; | ||
const BADSTR: string; | ||
const BADFLAGS: string; | ||
const NONAME: string; | ||
const BADHINTS: string; | ||
const NOTINITIALIZED: string; | ||
const LOADIPHLPAPI: string; | ||
const ADDRGETNETWORKPARAMS: string; | ||
const CANCELLED: string; | ||
class Resolver { | ||
export const NODATA: string; | ||
export const FORMERR: string; | ||
export const SERVFAIL: string; | ||
export const NOTFOUND: string; | ||
export const NOTIMP: string; | ||
export const REFUSED: string; | ||
export const BADQUERY: string; | ||
export const BADNAME: string; | ||
export const BADFAMILY: string; | ||
export const BADRESP: string; | ||
export const CONNREFUSED: string; | ||
export const TIMEOUT: string; | ||
export const EOF: string; | ||
export const FILE: string; | ||
export const NOMEM: string; | ||
export const DESTRUCTION: string; | ||
export const BADSTR: string; | ||
export const BADFLAGS: string; | ||
export const NONAME: string; | ||
export const BADHINTS: string; | ||
export const NOTINITIALIZED: string; | ||
export const LOADIPHLPAPI: string; | ||
export const ADDRGETNETWORKPARAMS: string; | ||
export const CANCELLED: string; | ||
export interface ResolverOptions { | ||
timeout?: number | undefined; | ||
/** | ||
* @default 4 | ||
*/ | ||
tries?: number; | ||
} | ||
/** | ||
* 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()` does not affect | ||
* other resolvers: | ||
* | ||
* ```js | ||
* const { Resolver } = require('node:dns'); | ||
* const resolver = new Resolver(); | ||
* resolver.setServers(['4.4.4.4']); | ||
* | ||
* // This request will use the server at 4.4.4.4, independent of global settings. | ||
* resolver.resolve4('example.org', (err, addresses) => { | ||
* // ... | ||
* }); | ||
* ``` | ||
* | ||
* The following methods from the `node:dns` module are available: | ||
* | ||
* * `resolver.getServers()` | ||
* * `resolver.resolve()` | ||
* * `resolver.resolve4()` | ||
* * `resolver.resolve6()` | ||
* * `resolver.resolveAny()` | ||
* * `resolver.resolveCaa()` | ||
* * `resolver.resolveCname()` | ||
* * `resolver.resolveMx()` | ||
* * `resolver.resolveNaptr()` | ||
* * `resolver.resolveNs()` | ||
* * `resolver.resolvePtr()` | ||
* * `resolver.resolveSoa()` | ||
* * `resolver.resolveSrv()` | ||
* * `resolver.resolveTxt()` | ||
* * `resolver.reverse()` | ||
* * `resolver.setServers()` | ||
* @since v8.3.0 | ||
*/ | ||
export class Resolver { | ||
constructor(options?: ResolverOptions); | ||
/** | ||
* Cancel all outstanding DNS queries made by this resolver. The corresponding | ||
* callbacks will be called with an error with code `ECANCELLED`. | ||
* @since v8.3.0 | ||
*/ | ||
cancel(): void; | ||
@@ -294,2 +785,3 @@ getServers: typeof getServers; | ||
resolveAny: typeof resolveAny; | ||
resolveCaa: typeof resolveCaa; | ||
resolveCname: typeof resolveCname; | ||
@@ -304,81 +796,24 @@ resolveMx: typeof resolveMx; | ||
reverse: typeof reverse; | ||
/** | ||
* The resolver instance will send its requests from the specified IP address. | ||
* This allows programs to specify outbound interfaces when used on multi-homed | ||
* systems. | ||
* | ||
* If a v4 or v6 address is not specified, it is set to the default and the | ||
* operating system will choose a local address automatically. | ||
* | ||
* The resolver will use the v4 local address when making requests to IPv4 DNS | ||
* servers, and the v6 local address when making requests to IPv6 DNS servers. | ||
* The `rrtype` of resolution requests has no impact on the local address used. | ||
* @since v15.1.0, v14.17.0 | ||
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. | ||
* @param [ipv6='::0'] A string representation of an IPv6 address. | ||
*/ | ||
setLocalAddress(ipv4?: string, ipv6?: string): void; | ||
setServers: typeof setServers; | ||
} | ||
namespace promises { | ||
function getServers(): string[]; | ||
function lookup(hostname: string, family: number): Promise<LookupAddress>; | ||
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>; | ||
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>; | ||
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>; | ||
function lookup(hostname: string): Promise<LookupAddress>; | ||
function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>; | ||
function resolve(hostname: string): Promise<string[]>; | ||
function resolve(hostname: string, rrtype: "A"): Promise<string[]>; | ||
function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>; | ||
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; | ||
function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>; | ||
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; | ||
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; | ||
function resolve(hostname: string, rrtype: "NS"): Promise<string[]>; | ||
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: "TXT"): Promise<string[][]>; | ||
function resolve(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; | ||
function resolve4(hostname: string): Promise<string[]>; | ||
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; | ||
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>; | ||
function resolve6(hostname: string): Promise<string[]>; | ||
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; | ||
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>; | ||
function resolveAny(hostname: string): Promise<AnyRecord[]>; | ||
function resolveCname(hostname: string): Promise<string[]>; | ||
function resolveMx(hostname: string): Promise<MxRecord[]>; | ||
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>; | ||
function resolveNs(hostname: string): Promise<string[]>; | ||
function resolvePtr(hostname: string): Promise<string[]>; | ||
function resolveSoa(hostname: string): Promise<SoaRecord>; | ||
function resolveSrv(hostname: string): Promise<SrvRecord[]>; | ||
function resolveTxt(hostname: string): Promise<string[][]>; | ||
function reverse(ip: string): Promise<string[]>; | ||
function setServers(servers: ReadonlyArray<string>): void; | ||
class Resolver { | ||
cancel(): void; | ||
getServers: typeof getServers; | ||
resolve: typeof resolve; | ||
resolve4: typeof resolve4; | ||
resolve6: typeof resolve6; | ||
resolveAny: typeof resolveAny; | ||
resolveCname: typeof resolveCname; | ||
resolveMx: typeof resolveMx; | ||
resolveNaptr: typeof resolveNaptr; | ||
resolveNs: typeof resolveNs; | ||
resolvePtr: typeof resolvePtr; | ||
resolveSoa: typeof resolveSoa; | ||
resolveSrv: typeof resolveSrv; | ||
resolveTxt: typeof resolveTxt; | ||
reverse: typeof reverse; | ||
setLocalAddress(ipv4?: string, ipv6?: string): void; | ||
setServers: typeof setServers; | ||
} | ||
} | ||
export { dnsPromises as promises }; | ||
} | ||
declare module "node:dns" { | ||
export * from "dns"; | ||
} |
@@ -0,24 +1,170 @@ | ||
/** | ||
* **This module is pending deprecation.** Once a replacement API has been | ||
* finalized, this module will be fully deprecated. Most developers should | ||
* **not** have cause to use this module. Users who absolutely must have | ||
* the functionality that domains provide may rely on it for the time being | ||
* but should expect to have to migrate to a different solution | ||
* in the future. | ||
* | ||
* Domains provide a way to handle multiple different IO operations as a | ||
* single group. If any of the event emitters or callbacks registered to a | ||
* domain emit an `'error'` event, or throw an error, then the domain object | ||
* 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/v20.2.0/lib/domain.js) | ||
*/ | ||
declare module "domain" { | ||
import { EventEmitter } from "events"; | ||
global { | ||
namespace NodeJS { | ||
interface Domain extends EventEmitter { | ||
run<T>(fn: (...args: any[]) => T, ...args: any[]): T; | ||
add(emitter: EventEmitter | Timer): void; | ||
remove(emitter: EventEmitter | Timer): void; | ||
bind<T extends Function>(cb: T): T; | ||
intercept<T extends Function>(cb: T): T; | ||
} | ||
} | ||
} | ||
interface Domain extends NodeJS.Domain {} | ||
import EventEmitter = require("node:events"); | ||
/** | ||
* The `Domain` class encapsulates the functionality of routing errors and | ||
* uncaught exceptions to the active `Domain` object. | ||
* | ||
* To handle the errors that it catches, listen to its `'error'` event. | ||
*/ | ||
class Domain extends EventEmitter { | ||
/** | ||
* An array of timers and event emitters that have been explicitly added | ||
* to the domain. | ||
*/ | ||
members: Array<EventEmitter | NodeJS.Timer>; | ||
/** | ||
* The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly | ||
* pushes the domain onto the domain | ||
* stack managed by the domain module (see {@link exit} for details on the | ||
* domain stack). The call to `enter()` delimits the beginning of a chain of | ||
* asynchronous calls and I/O operations bound to a domain. | ||
* | ||
* Calling `enter()` changes only the active domain, and does not alter the domain | ||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a | ||
* single domain. | ||
*/ | ||
enter(): void; | ||
/** | ||
* The `exit()` method exits the current domain, popping it off the domain stack. | ||
* Any time execution is going to switch to the context of a different chain of | ||
* asynchronous calls, it's important to ensure that the current domain is exited. | ||
* The call to `exit()` delimits either the end of or an interruption to the chain | ||
* of asynchronous calls and I/O operations bound to a domain. | ||
* | ||
* If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. | ||
* | ||
* Calling `exit()` changes only the active domain, and does not alter the domain | ||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a | ||
* single domain. | ||
*/ | ||
exit(): void; | ||
/** | ||
* Run the supplied function in the context of the domain, implicitly | ||
* binding all event emitters, timers, and low-level requests that are | ||
* created in that context. Optionally, arguments can be passed to | ||
* the function. | ||
* | ||
* This is the most basic way to use a domain. | ||
* | ||
* ```js | ||
* const domain = require('node:domain'); | ||
* const fs = require('node:fs'); | ||
* const d = domain.create(); | ||
* d.on('error', (er) => { | ||
* console.error('Caught error!', er); | ||
* }); | ||
* d.run(() => { | ||
* process.nextTick(() => { | ||
* setTimeout(() => { // Simulating some various async stuff | ||
* fs.open('non-existent file', 'r', (er, fd) => { | ||
* if (er) throw er; | ||
* // proceed... | ||
* }); | ||
* }, 100); | ||
* }); | ||
* }); | ||
* ``` | ||
* | ||
* In this example, the `d.on('error')` handler will be triggered, rather | ||
* than crashing the program. | ||
*/ | ||
run<T>(fn: (...args: any[]) => T, ...args: any[]): T; | ||
/** | ||
* Explicitly adds an emitter to the domain. If any event handlers called by | ||
* the emitter throw an error, or if the emitter emits an `'error'` event, it | ||
* will be routed to the domain's `'error'` event, just like with implicit | ||
* binding. | ||
* | ||
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by | ||
* the domain `'error'` handler. | ||
* | ||
* If the Timer or `EventEmitter` was already bound to a domain, it is removed | ||
* from that one, and bound to this one instead. | ||
* @param emitter emitter or timer to be added to the domain | ||
*/ | ||
add(emitter: EventEmitter | NodeJS.Timer): void; | ||
/** | ||
* The opposite of {@link add}. Removes domain handling from the | ||
* specified emitter. | ||
* @param emitter emitter or timer to be removed from the domain | ||
*/ | ||
remove(emitter: EventEmitter | NodeJS.Timer): void; | ||
/** | ||
* The returned function will be a wrapper around the supplied callback | ||
* function. When the returned function is called, any errors that are | ||
* thrown will be routed to the domain's `'error'` event. | ||
* | ||
* ```js | ||
* const d = domain.create(); | ||
* | ||
* function readSomeFile(filename, cb) { | ||
* fs.readFile(filename, 'utf8', d.bind((er, data) => { | ||
* // If this throws, it will also be passed to the domain. | ||
* return cb(er, data ? JSON.parse(data) : null); | ||
* })); | ||
* } | ||
* | ||
* d.on('error', (er) => { | ||
* // An error occurred somewhere. If we throw it now, it will crash the program | ||
* // with the normal line number and stack message. | ||
* }); | ||
* ``` | ||
* @param callback The callback function | ||
* @return The bound function | ||
*/ | ||
bind<T extends Function>(callback: T): T; | ||
/** | ||
* This method is almost identical to {@link bind}. However, in | ||
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. | ||
* | ||
* In this way, the common `if (err) return callback(err);` pattern can be replaced | ||
* with a single error handler in a single place. | ||
* | ||
* ```js | ||
* const d = domain.create(); | ||
* | ||
* function readSomeFile(filename, cb) { | ||
* fs.readFile(filename, 'utf8', d.intercept((data) => { | ||
* // Note, the first argument is never passed to the | ||
* // callback since it is assumed to be the 'Error' argument | ||
* // and thus intercepted by the domain. | ||
* | ||
* // If this throws, it will also be passed to the domain | ||
* // so the error-handling logic can be moved to the 'error' | ||
* // event on the domain instead of being repeated throughout | ||
* // the program. | ||
* return cb(null, JSON.parse(data)); | ||
* })); | ||
* } | ||
* | ||
* d.on('error', (er) => { | ||
* // An error occurred somewhere. If we throw it now, it will crash the program | ||
* // with the normal line number and stack message. | ||
* }); | ||
* ``` | ||
* @param callback The callback function | ||
* @return The intercepted function | ||
*/ | ||
intercept<T extends Function>(callback: T): T; | ||
} | ||
function create(): Domain; | ||
} | ||
declare module "node:domain" { | ||
export * from "domain"; | ||
} |
@@ -0,2 +1,72 @@ | ||
/** | ||
* Much of the Node.js core API is built around an idiomatic asynchronous | ||
* event-driven architecture in which certain kinds of objects (called "emitters") | ||
* emit named events that cause `Function` objects ("listeners") to be called. | ||
* | ||
* For instance: a `net.Server` object emits an event each time a peer | ||
* connects to it; a `fs.ReadStream` emits an event when the file is opened; | ||
* a `stream` emits an event whenever data is available to be read. | ||
* | ||
* All objects that emit events are instances of the `EventEmitter` class. These | ||
* objects expose an `eventEmitter.on()` function that allows one or more | ||
* functions to be attached to named events emitted by the object. Typically, | ||
* event names are camel-cased strings but any valid JavaScript property key | ||
* can be used. | ||
* | ||
* When the `EventEmitter` object emits an event, all of the functions attached | ||
* to that specific event are called _synchronously_. Any values returned by the | ||
* called listeners are _ignored_ and discarded. | ||
* | ||
* The following example shows a simple `EventEmitter` instance with a single | ||
* listener. The `eventEmitter.on()` method is used to register listeners, while | ||
* the `eventEmitter.emit()` method is used to trigger the event. | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* | ||
* class MyEmitter extends EventEmitter {} | ||
* | ||
* const myEmitter = new MyEmitter(); | ||
* myEmitter.on('event', () => { | ||
* console.log('an event occurred!'); | ||
* }); | ||
* myEmitter.emit('event'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js) | ||
*/ | ||
declare module "events" { | ||
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; | ||
// NOTE: This class is in the docs but is **not actually exported** by Node. | ||
// If https://github.com/nodejs/node/issues/39903 gets resolved and Node | ||
// actually starts exporting the class, uncomment below. | ||
// import { EventListener, EventListenerObject } from '__dom-events'; | ||
// /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ | ||
// interface NodeEventTarget extends EventTarget { | ||
// /** | ||
// * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. | ||
// * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. | ||
// */ | ||
// addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; | ||
// /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ | ||
// eventNames(): string[]; | ||
// /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ | ||
// listenerCount(type: string): number; | ||
// /** Node.js-specific alias for `eventTarget.removeListener()`. */ | ||
// off(type: string, listener: EventListener | EventListenerObject): this; | ||
// /** Node.js-specific alias for `eventTarget.addListener()`. */ | ||
// on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; | ||
// /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ | ||
// once(type: string, listener: EventListener | EventListenerObject): this; | ||
// /** | ||
// * Node.js-specific extension to the `EventTarget` class. | ||
// * If `type` is specified, removes all registered listeners for `type`, | ||
// * otherwise removes all registered listeners. | ||
// */ | ||
// removeAllListeners(type: string): this; | ||
// /** | ||
// * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. | ||
// * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. | ||
// */ | ||
// removeListener(type: string, listener: EventListener | EventListenerObject): this; | ||
// } | ||
interface EventEmitterOptions { | ||
@@ -6,73 +76,761 @@ /** | ||
*/ | ||
captureRejections?: boolean; | ||
captureRejections?: boolean | undefined; | ||
} | ||
interface NodeEventTarget { | ||
once(event: string | symbol, listener: (...args: any[]) => void): this; | ||
// Any EventTarget with a Node-style `once` function | ||
interface _NodeEventTarget { | ||
once(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
} | ||
interface DOMEventTarget { | ||
addEventListener(event: string, listener: (...args: any[]) => void, opts?: { once: boolean }): any; | ||
// Any EventTarget with a DOM-style `addEventListener` | ||
interface _DOMEventTarget { | ||
addEventListener( | ||
eventName: string, | ||
listener: (...args: any[]) => void, | ||
opts?: { | ||
once: boolean; | ||
}, | ||
): any; | ||
} | ||
interface StaticEventEmitterOptions { | ||
signal?: AbortSignal | undefined; | ||
} | ||
interface EventEmitter extends NodeJS.EventEmitter {} | ||
/** | ||
* The `EventEmitter` class is defined and exposed by the `node:events` module: | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* ``` | ||
* | ||
* All `EventEmitter`s emit the event `'newListener'` when new listeners are | ||
* added and `'removeListener'` when existing listeners are removed. | ||
* | ||
* It supports the following option: | ||
* @since v0.1.26 | ||
*/ | ||
class EventEmitter { | ||
constructor(options?: EventEmitterOptions); | ||
namespace EventEmitter { | ||
function once(emitter: NodeEventTarget, event: string | symbol): Promise<any[]>; | ||
function once(emitter: DOMEventTarget, event: string): Promise<any[]>; | ||
function on(emitter: EventEmitter, event: string): AsyncIterableIterator<any>; | ||
const captureRejectionSymbol: unique symbol; | ||
[EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; | ||
/** | ||
* This symbol shall be used to install a listener for only monitoring `'error'` | ||
* events. Listeners installed using this symbol are called before the regular | ||
* `'error'` listeners are called. | ||
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given | ||
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting. | ||
* The `Promise` will resolve with an array of all the arguments emitted to the | ||
* given event. | ||
* | ||
* Installing a listener using this symbol does not change the behavior once an | ||
* `'error'` event is emitted, therefore the process will still crash if no | ||
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event | ||
* semantics and does not listen to the `'error'` event. | ||
* | ||
* ```js | ||
* import { once, EventEmitter } from 'node:events'; | ||
* import process from 'node:process'; | ||
* | ||
* const ee = new EventEmitter(); | ||
* | ||
* process.nextTick(() => { | ||
* ee.emit('myevent', 42); | ||
* }); | ||
* | ||
* const [value] = await once(ee, 'myevent'); | ||
* console.log(value); | ||
* | ||
* const err = new Error('kaboom'); | ||
* process.nextTick(() => { | ||
* ee.emit('error', err); | ||
* }); | ||
* | ||
* try { | ||
* await once(ee, 'myevent'); | ||
* } catch (err) { | ||
* console.error('error happened', err); | ||
* } | ||
* ``` | ||
* | ||
* The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the | ||
* '`error'` event itself, then it is treated as any other kind of event without | ||
* special handling: | ||
* | ||
* ```js | ||
* import { EventEmitter, once } from 'node:events'; | ||
* | ||
* const ee = new EventEmitter(); | ||
* | ||
* once(ee, 'error') | ||
* .then(([err]) => console.log('ok', err.message)) | ||
* .catch((err) => console.error('error', err.message)); | ||
* | ||
* ee.emit('error', new Error('boom')); | ||
* | ||
* // Prints: ok boom | ||
* ``` | ||
* | ||
* An `AbortSignal` can be used to cancel waiting for the event: | ||
* | ||
* ```js | ||
* import { EventEmitter, once } from 'node:events'; | ||
* | ||
* const ee = new EventEmitter(); | ||
* const ac = new AbortController(); | ||
* | ||
* async function foo(emitter, event, signal) { | ||
* try { | ||
* await once(emitter, event, { signal }); | ||
* console.log('event emitted!'); | ||
* } catch (error) { | ||
* if (error.name === 'AbortError') { | ||
* console.error('Waiting for the event was canceled!'); | ||
* } else { | ||
* console.error('There was an error', error.message); | ||
* } | ||
* } | ||
* } | ||
* | ||
* foo(ee, 'foo', ac.signal); | ||
* ac.abort(); // Abort waiting for the event | ||
* ee.emit('foo'); // Prints: Waiting for the event was canceled! | ||
* ``` | ||
* @since v11.13.0, v10.16.0 | ||
*/ | ||
static once( | ||
emitter: _NodeEventTarget, | ||
eventName: string | symbol, | ||
options?: StaticEventEmitterOptions, | ||
): Promise<any[]>; | ||
static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>; | ||
/** | ||
* ```js | ||
* import { on, EventEmitter } from 'node:events'; | ||
* import process from 'node:process'; | ||
* | ||
* const ee = new EventEmitter(); | ||
* | ||
* // Emit later on | ||
* process.nextTick(() => { | ||
* ee.emit('foo', 'bar'); | ||
* ee.emit('foo', 42); | ||
* }); | ||
* | ||
* for await (const event of on(ee, 'foo')) { | ||
* // The execution of this inner block is synchronous and it | ||
* // processes one event at a time (even with await). Do not use | ||
* // if concurrent execution is required. | ||
* console.log(event); // prints ['bar'] [42] | ||
* } | ||
* // Unreachable here | ||
* ``` | ||
* | ||
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw | ||
* if the `EventEmitter` emits `'error'`. It removes all listeners when | ||
* exiting the loop. The `value` returned by each iteration is an array | ||
* composed of the emitted event arguments. | ||
* | ||
* An `AbortSignal` can be used to cancel waiting on events: | ||
* | ||
* ```js | ||
* import { on, EventEmitter } from 'node:events'; | ||
* import process from 'node:process'; | ||
* | ||
* const ac = new AbortController(); | ||
* | ||
* (async () => { | ||
* const ee = new EventEmitter(); | ||
* | ||
* // Emit later on | ||
* process.nextTick(() => { | ||
* ee.emit('foo', 'bar'); | ||
* ee.emit('foo', 42); | ||
* }); | ||
* | ||
* for await (const event of on(ee, 'foo', { signal: ac.signal })) { | ||
* // The execution of this inner block is synchronous and it | ||
* // processes one event at a time (even with await). Do not use | ||
* // if concurrent execution is required. | ||
* console.log(event); // prints ['bar'] [42] | ||
* } | ||
* // Unreachable here | ||
* })(); | ||
* | ||
* process.nextTick(() => ac.abort()); | ||
* ``` | ||
* @since v13.6.0, v12.16.0 | ||
* @param eventName The name of the event being listened for | ||
* @return that iterates `eventName` events emitted by the `emitter` | ||
*/ | ||
static on( | ||
emitter: NodeJS.EventEmitter, | ||
eventName: string, | ||
options?: StaticEventEmitterOptions, | ||
): AsyncIterableIterator<any>; | ||
/** | ||
* A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. | ||
* | ||
* ```js | ||
* import { EventEmitter, listenerCount } from 'node:events'; | ||
* | ||
* const myEmitter = new EventEmitter(); | ||
* myEmitter.on('event', () => {}); | ||
* myEmitter.on('event', () => {}); | ||
* console.log(listenerCount(myEmitter, 'event')); | ||
* // Prints: 2 | ||
* ``` | ||
* @since v0.9.12 | ||
* @deprecated Since v3.2.0 - Use `listenerCount` instead. | ||
* @param emitter The emitter to query | ||
* @param eventName The event name | ||
*/ | ||
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; | ||
/** | ||
* Returns a copy of the array of listeners for the event named `eventName`. | ||
* | ||
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on | ||
* the emitter. | ||
* | ||
* For `EventTarget`s this is the only way to get the event listeners for the | ||
* event target. This is useful for debugging and diagnostic purposes. | ||
* | ||
* ```js | ||
* import { getEventListeners, EventEmitter } from 'node:events'; | ||
* | ||
* { | ||
* const ee = new EventEmitter(); | ||
* const listener = () => console.log('Events are fun'); | ||
* ee.on('foo', listener); | ||
* console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] | ||
* } | ||
* { | ||
* const et = new EventTarget(); | ||
* const listener = () => console.log('Events are fun'); | ||
* et.addEventListener('foo', listener); | ||
* console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] | ||
* } | ||
* ``` | ||
* @since v15.2.0, v14.17.0 | ||
*/ | ||
static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; | ||
/** | ||
* Returns the currently set max amount of listeners. | ||
* | ||
* For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on | ||
* the emitter. | ||
* | ||
* For `EventTarget`s this is the only way to get the max event listeners for the | ||
* event target. If the number of event handlers on a single EventTarget exceeds | ||
* the max set, the EventTarget will print a warning. | ||
* | ||
* ```js | ||
* import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; | ||
* | ||
* { | ||
* const ee = new EventEmitter(); | ||
* console.log(getMaxListeners(ee)); // 10 | ||
* setMaxListeners(11, ee); | ||
* console.log(getMaxListeners(ee)); // 11 | ||
* } | ||
* { | ||
* const et = new EventTarget(); | ||
* console.log(getMaxListeners(et)); // 10 | ||
* setMaxListeners(11, et); | ||
* console.log(getMaxListeners(et)); // 11 | ||
* } | ||
* ``` | ||
* @since v19.9.0 | ||
*/ | ||
static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; | ||
/** | ||
* ```js | ||
* import { setMaxListeners, EventEmitter } from 'node:events'; | ||
* | ||
* const target = new EventTarget(); | ||
* const emitter = new EventEmitter(); | ||
* | ||
* setMaxListeners(5, target, emitter); | ||
* ``` | ||
* @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} | ||
* objects. | ||
*/ | ||
static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void; | ||
/** | ||
* Listens once to the `abort` event on the provided `signal`. | ||
* | ||
* Listening to the `abort` event on abort signals is unsafe and may | ||
* lead to resource leaks since another third party with the signal can | ||
* call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change | ||
* this since it would violate the web standard. Additionally, the original | ||
* API makes it easy to forget to remove listeners. | ||
* | ||
* This API allows safely using `AbortSignal`s in Node.js APIs by solving these | ||
* two issues by listening to the event such that `stopImmediatePropagation` does | ||
* not prevent the listener from running. | ||
* | ||
* Returns a disposable so that it may be unsubscribed from more easily. | ||
* | ||
* ```js | ||
* import { addAbortListener } from 'node:events'; | ||
* | ||
* function example(signal) { | ||
* let disposable; | ||
* try { | ||
* signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); | ||
* disposable = addAbortListener(signal, (e) => { | ||
* // Do something when signal is aborted. | ||
* }); | ||
* } finally { | ||
* disposable?.[Symbol.dispose](); | ||
* } | ||
* } | ||
* ``` | ||
* @since v20.5.0 | ||
* @experimental | ||
* @return Disposable that removes the `abort` listener. | ||
*/ | ||
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; | ||
/** | ||
* This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called. | ||
* | ||
* Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no | ||
* regular `'error'` listener is installed. | ||
* @since v13.6.0, v12.17.0 | ||
*/ | ||
const errorMonitor: unique symbol; | ||
static readonly errorMonitor: unique symbol; | ||
/** | ||
* Sets or gets the default captureRejection value for all emitters. | ||
* Value: `Symbol.for('nodejs.rejection')` | ||
* | ||
* See how to write a custom `rejection handler`. | ||
* @since v13.4.0, v12.16.0 | ||
*/ | ||
let captureRejections: boolean; | ||
static readonly captureRejectionSymbol: unique symbol; | ||
/** | ||
* Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | ||
* | ||
* Change the default `captureRejections` option on all new `EventEmitter` objects. | ||
* @since v13.4.0, v12.16.0 | ||
*/ | ||
static captureRejections: boolean; | ||
/** | ||
* By default, a maximum of `10` listeners can be registered for any single | ||
* event. This limit can be changed for individual `EventEmitter` instances | ||
* using the `emitter.setMaxListeners(n)` method. To change the default | ||
* for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. | ||
* | ||
* Take caution when setting the `events.defaultMaxListeners` because the | ||
* change affects _all_`EventEmitter` instances, including those created before | ||
* the change is made. However, calling `emitter.setMaxListeners(n)` still has | ||
* precedence over `events.defaultMaxListeners`. | ||
* | ||
* This is not a hard limit. The `EventEmitter` instance will allow | ||
* more listeners to be added but will output a trace warning to stderr indicating | ||
* that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to | ||
* temporarily avoid this warning: | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* const emitter = new EventEmitter(); | ||
* emitter.setMaxListeners(emitter.getMaxListeners() + 1); | ||
* emitter.once('event', () => { | ||
* // do stuff | ||
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); | ||
* }); | ||
* ``` | ||
* | ||
* The `--trace-warnings` command-line flag can be used to display the | ||
* stack trace for such warnings. | ||
* | ||
* The emitted warning can be inspected with `process.on('warning')` and will | ||
* have the additional `emitter`, `type`, and `count` properties, referring to | ||
* the event emitter instance, the event's name and the number of attached | ||
* listeners, respectively. | ||
* Its `name` property is set to `'MaxListenersExceededWarning'`. | ||
* @since v0.11.2 | ||
*/ | ||
static defaultMaxListeners: number; | ||
} | ||
import internal = require("node:events"); | ||
namespace EventEmitter { | ||
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 | ||
export { internal as EventEmitter }; | ||
export interface Abortable { | ||
/** | ||
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action. | ||
*/ | ||
signal?: AbortSignal | undefined; | ||
} | ||
interface EventEmitter extends NodeJS.EventEmitter { | ||
export interface EventEmitterReferencingAsyncResource extends AsyncResource { | ||
readonly eventEmitter: EventEmitterAsyncResource; | ||
} | ||
class EventEmitter { | ||
constructor(options?: EventEmitterOptions); | ||
/** @deprecated since v4.0.0 */ | ||
static listenerCount(emitter: EventEmitter, event: string | symbol): number; | ||
static defaultMaxListeners: number; | ||
export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { | ||
/** | ||
* This symbol shall be used to install a listener for only monitoring `'error'` | ||
* events. Listeners installed using this symbol are called before the regular | ||
* `'error'` listeners are called. | ||
* | ||
* Installing a listener using this symbol does not change the behavior once an | ||
* `'error'` event is emitted, therefore the process will still crash if no | ||
* regular `'error'` listener is installed. | ||
* The type of async event, this is required when instantiating `EventEmitterAsyncResource` | ||
* directly rather than as a child class. | ||
* @default new.target.name if instantiated as a child class. | ||
*/ | ||
static readonly errorMonitor: unique symbol; | ||
name?: string; | ||
} | ||
/** | ||
* Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that require | ||
* manual async tracking. Specifically, all events emitted by instances of | ||
* `EventEmitterAsyncResource` will run within its async context. | ||
* | ||
* The EventEmitterAsyncResource class has the same methods and takes the | ||
* same options as EventEmitter and AsyncResource themselves. | ||
* @throws if `options.name` is not provided when instantiated directly. | ||
* @since v17.4.0, v16.14.0 | ||
*/ | ||
export class EventEmitterAsyncResource extends EventEmitter { | ||
/** | ||
* @param options Only optional in child class. | ||
*/ | ||
constructor(options?: EventEmitterAsyncResourceOptions); | ||
/** | ||
* Call all destroy hooks. This should only ever be called once. An | ||
* error will be thrown if it is called more than once. This must be | ||
* manually called. If the resource is left to be collected by the GC then | ||
* the destroy hooks will never be called. | ||
*/ | ||
emitDestroy(): void; | ||
/** The unique asyncId assigned to the resource. */ | ||
readonly asyncId: number; | ||
/** The same triggerAsyncId that is passed to the AsyncResource constructor. */ | ||
readonly triggerAsyncId: number; | ||
/** The underlying AsyncResource */ | ||
readonly asyncResource: EventEmitterReferencingAsyncResource; | ||
} | ||
} | ||
global { | ||
namespace NodeJS { | ||
interface EventEmitter { | ||
addListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
on(event: string | symbol, listener: (...args: any[]) => void): this; | ||
once(event: string | symbol, listener: (...args: any[]) => void): this; | ||
removeListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
off(event: string | symbol, listener: (...args: any[]) => void): this; | ||
[EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; | ||
/** | ||
* Alias for `emitter.on(eventName, listener)`. | ||
* @since v0.1.26 | ||
*/ | ||
addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Adds the `listener` function to the end of the listeners array for the | ||
* event named `eventName`. No checks are made to see if the `listener` has | ||
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple | ||
* times. | ||
* | ||
* ```js | ||
* server.on('connection', (stream) => { | ||
* console.log('someone connected!'); | ||
* }); | ||
* ``` | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* | ||
* By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the | ||
* event listener to the beginning of the listeners array. | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* const myEE = new EventEmitter(); | ||
* myEE.on('foo', () => console.log('a')); | ||
* myEE.prependListener('foo', () => console.log('b')); | ||
* myEE.emit('foo'); | ||
* // Prints: | ||
* // b | ||
* // a | ||
* ``` | ||
* @since v0.1.101 | ||
* @param eventName The name of the event. | ||
* @param listener The callback function | ||
*/ | ||
on(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Adds a **one-time**`listener` function for the event named `eventName`. The | ||
* next time `eventName` is triggered, this listener is removed and then invoked. | ||
* | ||
* ```js | ||
* server.once('connection', (stream) => { | ||
* console.log('Ah, we have our first user!'); | ||
* }); | ||
* ``` | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* | ||
* By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the | ||
* event listener to the beginning of the listeners array. | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* const myEE = new EventEmitter(); | ||
* myEE.once('foo', () => console.log('a')); | ||
* myEE.prependOnceListener('foo', () => console.log('b')); | ||
* myEE.emit('foo'); | ||
* // Prints: | ||
* // b | ||
* // a | ||
* ``` | ||
* @since v0.3.0 | ||
* @param eventName The name of the event. | ||
* @param listener The callback function | ||
*/ | ||
once(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Removes the specified `listener` from the listener array for the event named`eventName`. | ||
* | ||
* ```js | ||
* const callback = (stream) => { | ||
* console.log('someone connected!'); | ||
* }; | ||
* server.on('connection', callback); | ||
* // ... | ||
* server.removeListener('connection', callback); | ||
* ``` | ||
* | ||
* `removeListener()` will remove, at most, one instance of a listener from the | ||
* listener array. If any single listener has been added multiple times to the | ||
* listener array for the specified `eventName`, then `removeListener()` must be | ||
* called multiple times to remove each instance. | ||
* | ||
* Once an event is emitted, all listeners attached to it at the | ||
* time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution | ||
* will not remove them from`emit()` in progress. Subsequent events behave as expected. | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* class MyEmitter extends EventEmitter {} | ||
* const myEmitter = new MyEmitter(); | ||
* | ||
* const callbackA = () => { | ||
* console.log('A'); | ||
* myEmitter.removeListener('event', callbackB); | ||
* }; | ||
* | ||
* const callbackB = () => { | ||
* console.log('B'); | ||
* }; | ||
* | ||
* myEmitter.on('event', callbackA); | ||
* | ||
* myEmitter.on('event', callbackB); | ||
* | ||
* // callbackA removes listener callbackB but it will still be called. | ||
* // Internal listener array at time of emit [callbackA, callbackB] | ||
* myEmitter.emit('event'); | ||
* // Prints: | ||
* // A | ||
* // B | ||
* | ||
* // callbackB is now removed. | ||
* // Internal listener array [callbackA] | ||
* myEmitter.emit('event'); | ||
* // Prints: | ||
* // A | ||
* ``` | ||
* | ||
* Because listeners are managed using an internal array, calling this will | ||
* change the position indices of any listener registered _after_ the listener | ||
* being removed. This will not impact the order in which listeners are called, | ||
* but it means that any copies of the listener array as returned by | ||
* the `emitter.listeners()` method will need to be recreated. | ||
* | ||
* When a single function has been added as a handler multiple times for a single | ||
* event (as in the example below), `removeListener()` will remove the most | ||
* recently added instance. In the example the `once('ping')`listener is removed: | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* const ee = new EventEmitter(); | ||
* | ||
* function pong() { | ||
* console.log('pong'); | ||
* } | ||
* | ||
* ee.on('ping', pong); | ||
* ee.once('ping', pong); | ||
* ee.removeListener('ping', pong); | ||
* | ||
* ee.emit('ping'); | ||
* ee.emit('ping'); | ||
* ``` | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* @since v0.1.26 | ||
*/ | ||
removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Alias for `emitter.removeListener()`. | ||
* @since v10.0.0 | ||
*/ | ||
off(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Removes all listeners, or those of the specified `eventName`. | ||
* | ||
* It is bad practice to remove listeners added elsewhere in the code, | ||
* particularly when the `EventEmitter` instance was created by some other | ||
* component or module (e.g. sockets or file streams). | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* @since v0.1.26 | ||
*/ | ||
removeAllListeners(event?: string | symbol): this; | ||
/** | ||
* By default `EventEmitter`s will print a warning if more than `10` listeners are | ||
* added for a particular event. This is a useful default that helps finding | ||
* memory leaks. The `emitter.setMaxListeners()` method allows the limit to be | ||
* modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* @since v0.3.5 | ||
*/ | ||
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}. | ||
* @since v1.0.0 | ||
*/ | ||
getMaxListeners(): number; | ||
listeners(event: string | symbol): Function[]; | ||
rawListeners(event: string | symbol): Function[]; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
listenerCount(event: string | symbol): number; | ||
// Added in Node 6... | ||
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Returns a copy of the array of listeners for the event named `eventName`. | ||
* | ||
* ```js | ||
* server.on('connection', (stream) => { | ||
* console.log('someone connected!'); | ||
* }); | ||
* console.log(util.inspect(server.listeners('connection'))); | ||
* // Prints: [ [Function] ] | ||
* ``` | ||
* @since v0.1.26 | ||
*/ | ||
listeners(eventName: string | symbol): Function[]; | ||
/** | ||
* Returns a copy of the array of listeners for the event named `eventName`, | ||
* including any wrappers (such as those created by `.once()`). | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* const emitter = new EventEmitter(); | ||
* emitter.once('log', () => console.log('log once')); | ||
* | ||
* // Returns a new Array with a function `onceWrapper` which has a property | ||
* // `listener` which contains the original listener bound above | ||
* const listeners = emitter.rawListeners('log'); | ||
* const logFnWrapper = listeners[0]; | ||
* | ||
* // Logs "log once" to the console and does not unbind the `once` event | ||
* logFnWrapper.listener(); | ||
* | ||
* // Logs "log once" to the console and removes the listener | ||
* logFnWrapper(); | ||
* | ||
* emitter.on('log', () => console.log('log persistently')); | ||
* // Will return a new Array with a single function bound by `.on()` above | ||
* const newListeners = emitter.rawListeners('log'); | ||
* | ||
* // Logs "log persistently" twice | ||
* newListeners[0](); | ||
* emitter.emit('log'); | ||
* ``` | ||
* @since v9.4.0 | ||
*/ | ||
rawListeners(eventName: string | symbol): Function[]; | ||
/** | ||
* Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments | ||
* to each. | ||
* | ||
* Returns `true` if the event had listeners, `false` otherwise. | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* const myEmitter = new EventEmitter(); | ||
* | ||
* // First listener | ||
* myEmitter.on('event', function firstListener() { | ||
* console.log('Helloooo! first listener'); | ||
* }); | ||
* // Second listener | ||
* myEmitter.on('event', function secondListener(arg1, arg2) { | ||
* console.log(`event with parameters ${arg1}, ${arg2} in second listener`); | ||
* }); | ||
* // Third listener | ||
* myEmitter.on('event', function thirdListener(...args) { | ||
* const parameters = args.join(', '); | ||
* console.log(`event with parameters ${parameters} in third listener`); | ||
* }); | ||
* | ||
* console.log(myEmitter.listeners('event')); | ||
* | ||
* myEmitter.emit('event', 1, 2, 3, 4, 5); | ||
* | ||
* // Prints: | ||
* // [ | ||
* // [Function: firstListener], | ||
* // [Function: secondListener], | ||
* // [Function: thirdListener] | ||
* // ] | ||
* // Helloooo! first listener | ||
* // event with parameters 1, 2 in second listener | ||
* // event with parameters 1, 2, 3, 4, 5 in third listener | ||
* ``` | ||
* @since v0.1.26 | ||
*/ | ||
emit(eventName: string | symbol, ...args: any[]): boolean; | ||
/** | ||
* Returns the number of listeners listening for the event named `eventName`. | ||
* If `listener` is provided, it will return how many times the listener is found | ||
* in the list of the listeners of the event. | ||
* @since v3.2.0 | ||
* @param eventName The name of the event being listened for | ||
* @param listener The event handler function | ||
*/ | ||
listenerCount(eventName: string | symbol, listener?: Function): number; | ||
/** | ||
* Adds the `listener` function to the _beginning_ of the listeners array for the | ||
* event named `eventName`. No checks are made to see if the `listener` has | ||
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple | ||
* times. | ||
* | ||
* ```js | ||
* server.prependListener('connection', (stream) => { | ||
* console.log('someone connected!'); | ||
* }); | ||
* ``` | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* @since v6.0.0 | ||
* @param eventName The name of the event. | ||
* @param listener The callback function | ||
*/ | ||
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this | ||
* listener is removed, and then invoked. | ||
* | ||
* ```js | ||
* server.prependOnceListener('connection', (stream) => { | ||
* console.log('Ah, we have our first user!'); | ||
* }); | ||
* ``` | ||
* | ||
* Returns a reference to the `EventEmitter`, so that calls can be chained. | ||
* @since v6.0.0 | ||
* @param eventName The name of the event. | ||
* @param listener The callback function | ||
*/ | ||
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; | ||
/** | ||
* Returns an array listing the events for which the emitter has registered | ||
* listeners. The values in the array are strings or `Symbol`s. | ||
* | ||
* ```js | ||
* import { EventEmitter } from 'node:events'; | ||
* | ||
* const myEE = new EventEmitter(); | ||
* myEE.on('foo', () => {}); | ||
* myEE.on('bar', () => {}); | ||
* | ||
* const sym = Symbol('symbol'); | ||
* myEE.on(sym, () => {}); | ||
* | ||
* console.log(myEE.eventNames()); | ||
* // Prints: [ 'foo', 'bar', Symbol(symbol) ] | ||
* ``` | ||
* @since v6.0.0 | ||
*/ | ||
eventNames(): Array<string | symbol>; | ||
@@ -82,4 +840,7 @@ } | ||
} | ||
export = EventEmitter; | ||
} | ||
declare module "node:events" { | ||
import events = require("events"); | ||
export = events; | ||
} |
@@ -1,77 +0,281 @@ | ||
declare module 'fs/promises' { | ||
/** | ||
* The `fs/promises` API provides asynchronous file system methods that return | ||
* promises. | ||
* | ||
* The promise APIs use the underlying Node.js threadpool to perform file | ||
* system operations off the event loop thread. These operations are not | ||
* synchronized or threadsafe. Care must be taken when performing multiple | ||
* concurrent modifications on the same file or data corruption may occur. | ||
* @since v10.0.0 | ||
*/ | ||
declare module "fs/promises" { | ||
import { Abortable } from "node:events"; | ||
import { Stream } from "node:stream"; | ||
import { ReadableStream } from "node:stream/web"; | ||
import { | ||
Stats, | ||
WriteVResult, | ||
BigIntStats, | ||
BigIntStatsFs, | ||
BufferEncodingOption, | ||
constants as fsConstants, | ||
CopyOptions, | ||
Dir, | ||
Dirent, | ||
MakeDirectoryOptions, | ||
Mode, | ||
ObjectEncodingOptions, | ||
OpenDirOptions, | ||
OpenMode, | ||
PathLike, | ||
ReadStream, | ||
ReadVResult, | ||
PathLike, | ||
RmDirOptions, | ||
RmOptions, | ||
MakeDirectoryOptions, | ||
Dirent, | ||
OpenDirOptions, | ||
Dir, | ||
BaseEncodingOptions, | ||
BufferEncodingOption, | ||
OpenMode, | ||
Mode, | ||
} from 'fs'; | ||
StatFsOptions, | ||
StatOptions, | ||
Stats, | ||
StatsFs, | ||
TimeLike, | ||
WatchEventType, | ||
WatchOptions, | ||
WriteStream, | ||
WriteVResult, | ||
} from "node:fs"; | ||
import { Interface as ReadlineInterface } from "node:readline"; | ||
interface FileChangeInfo<T extends string | Buffer> { | ||
eventType: WatchEventType; | ||
filename: T | null; | ||
} | ||
interface FlagAndOpenMode { | ||
mode?: Mode | undefined; | ||
flag?: OpenMode | undefined; | ||
} | ||
interface FileReadResult<T extends NodeJS.ArrayBufferView> { | ||
bytesRead: number; | ||
buffer: T; | ||
} | ||
interface FileReadOptions<T extends NodeJS.ArrayBufferView = Buffer> { | ||
/** | ||
* @default `Buffer.alloc(0xffff)` | ||
*/ | ||
buffer?: T; | ||
/** | ||
* @default 0 | ||
*/ | ||
offset?: number | null; | ||
/** | ||
* @default `buffer.byteLength` | ||
*/ | ||
length?: number | null; | ||
position?: number | null; | ||
} | ||
interface CreateReadStreamOptions { | ||
encoding?: BufferEncoding | null | undefined; | ||
autoClose?: boolean | undefined; | ||
emitClose?: boolean | undefined; | ||
start?: number | undefined; | ||
end?: number | undefined; | ||
highWaterMark?: number | undefined; | ||
} | ||
interface CreateWriteStreamOptions { | ||
encoding?: BufferEncoding | null | undefined; | ||
autoClose?: boolean | undefined; | ||
emitClose?: boolean | undefined; | ||
start?: number | undefined; | ||
highWaterMark?: number | 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 { | ||
/** | ||
* Gets the file descriptor for this file handle. | ||
* The numeric file descriptor managed by the {FileHandle} object. | ||
* @since v10.0.0 | ||
*/ | ||
readonly fd: number; | ||
/** | ||
* Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. | ||
* The `FileHandle` must have been opened for appending. | ||
* @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. | ||
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. | ||
* If `encoding` is not supplied, the default of `'utf8'` is used. | ||
* If `mode` is not supplied, the default of `0o666` is used. | ||
* If `mode` is a string, it is parsed as an octal integer. | ||
* If `flag` is not supplied, the default of `'a'` is used. | ||
* Alias of `filehandle.writeFile()`. | ||
* | ||
* When operating on file handles, the mode cannot be changed from what it was set | ||
* to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
appendFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise<void>; | ||
appendFile( | ||
data: string | Uint8Array, | ||
options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null, | ||
): Promise<void>; | ||
/** | ||
* Asynchronous fchown(2) - Change ownership of a file. | ||
* Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). | ||
* @since v10.0.0 | ||
* @param uid The file's new owner's user id. | ||
* @param gid The file's new group's group id. | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
chown(uid: number, gid: number): Promise<void>; | ||
/** | ||
* Asynchronous fchmod(2) - Change permissions of a file. | ||
* @param mode A file mode. If a string is passed, it is parsed as an octal integer. | ||
* Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). | ||
* @since v10.0.0 | ||
* @param mode the file mode bit mask. | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
chmod(mode: Mode): Promise<void>; | ||
/** | ||
* Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. | ||
* 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 | ||
* \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is | ||
* omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from | ||
* the current file position. The `encoding` can be any one of those accepted by `Buffer`. | ||
* | ||
* If the `FileHandle` points to a character device that only supports blocking | ||
* reads (such as keyboard or sound card), read operations do not finish until data | ||
* is available. This can prevent the process from exiting and the stream from | ||
* closing naturally. | ||
* | ||
* By default, the stream will emit a `'close'` event after it has been | ||
* destroyed. Set the `emitClose` option to `false` to change this behavior. | ||
* | ||
* ```js | ||
* import { open } from 'node:fs/promises'; | ||
* | ||
* const fd = await open('/dev/input/event0'); | ||
* // Create a stream from some character device. | ||
* const stream = fd.createReadStream(); | ||
* setTimeout(() => { | ||
* stream.close(); // This may not close the stream. | ||
* // Artificially marking end-of-stream, as if the underlying resource had | ||
* // indicated end-of-file by itself, allows the stream to close. | ||
* // This does not cancel pending read operations, and if there is such an | ||
* // operation, the process may still not be able to exit successfully | ||
* // until it finishes. | ||
* stream.push(null); | ||
* stream.read(0); | ||
* }, 100); | ||
* ``` | ||
* | ||
* If `autoClose` is false, then the file descriptor won't be closed, even if | ||
* there's an error. It is the application's responsibility to close it and make | ||
* sure there's no file descriptor leak. If `autoClose` is set to true (default | ||
* behavior), on `'error'` or `'end'` the file descriptor will be closed | ||
* automatically. | ||
* | ||
* An example to read the last 10 bytes of a file which is 100 bytes long: | ||
* | ||
* ```js | ||
* import { open } from 'node:fs/promises'; | ||
* | ||
* const fd = await open('sample.txt'); | ||
* fd.createReadStream({ start: 90, end: 99 }); | ||
* ``` | ||
* @since v16.11.0 | ||
*/ | ||
createReadStream(options?: CreateReadStreamOptions): ReadStream; | ||
/** | ||
* `options` may also include a `start` option to allow writing data at some | ||
* position past the beginning of the file, allowed values are in the | ||
* \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than | ||
* replacing it may require the `flags` `open` option to be set to `r+` rather than | ||
* the default `r`. The `encoding` can be any one of those accepted by `Buffer`. | ||
* | ||
* If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, | ||
* then the file descriptor won't be closed, even if there's an error. | ||
* It is the application's responsibility to close it and make sure there's no | ||
* file descriptor leak. | ||
* | ||
* By default, the stream will emit a `'close'` event after it has been | ||
* destroyed. Set the `emitClose` option to `false` to change this behavior. | ||
* @since v16.11.0 | ||
*/ | ||
createWriteStream(options?: CreateWriteStreamOptions): WriteStream; | ||
/** | ||
* Forces all currently queued I/O operations associated with the file to the | ||
* operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. | ||
* | ||
* Unlike `filehandle.sync` this method does not flush modified metadata. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
datasync(): Promise<void>; | ||
/** | ||
* Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. | ||
* Request that all data for the open file descriptor is flushed to the storage | ||
* device. The specific implementation is operating system and device specific. | ||
* Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
sync(): Promise<void>; | ||
/** | ||
* Asynchronously reads data from the file. | ||
* The `FileHandle` must have been opened for reading. | ||
* @param buffer The buffer that the data will be written to. | ||
* @param offset The offset in the buffer at which to start writing. | ||
* Reads data from the file and stores that in the given buffer. | ||
* | ||
* If the file is not modified concurrently, the end-of-file is reached when the | ||
* number of bytes read is zero. | ||
* @since v10.0.0 | ||
* @param buffer A buffer that will be filled with the file data read. | ||
* @param offset The location in the buffer at which to start filling. | ||
* @param length The number of bytes to read. | ||
* @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. | ||
* @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an | ||
* integer, the current file position will remain unchanged. | ||
* @return Fulfills upon success with an object with two properties: | ||
*/ | ||
read<TBuffer extends Uint8Array>(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; | ||
read<T extends NodeJS.ArrayBufferView>( | ||
buffer: T, | ||
offset?: number | null, | ||
length?: number | null, | ||
position?: number | null, | ||
): Promise<FileReadResult<T>>; | ||
read<T extends NodeJS.ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>>; | ||
/** | ||
* 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'`. | ||
* Returns a `ReadableStream` that may be used to read the files data. | ||
* | ||
* An error will be thrown if this method is called more than once or is called | ||
* after the `FileHandle` is closed or closing. | ||
* | ||
* ```js | ||
* import { | ||
* open, | ||
* } from 'node:fs/promises'; | ||
* | ||
* const file = await open('./some/file/to/read'); | ||
* | ||
* for await (const chunk of file.readableWebStream()) | ||
* console.log(chunk); | ||
* | ||
* await file.close(); | ||
* ``` | ||
* | ||
* 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 | ||
*/ | ||
readFile(options?: { encoding?: null, flag?: OpenMode } | null): Promise<Buffer>; | ||
readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; | ||
/** | ||
* Asynchronously reads the entire contents of a file. | ||
* | ||
* If `options` is a string, then it specifies the `encoding`. | ||
* | ||
* The `FileHandle` has to support reading. | ||
* | ||
* If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current | ||
* position till the end of the file. It doesn't always read from the beginning | ||
* of the file. | ||
* @since v10.0.0 | ||
* @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the | ||
* data will be a string. | ||
*/ | ||
readFile( | ||
options?: { | ||
encoding?: null | undefined; | ||
flag?: OpenMode | undefined; | ||
} | null, | ||
): Promise<Buffer>; | ||
/** | ||
* Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. | ||
@@ -82,4 +286,10 @@ * The `FileHandle` must have been opened for reading. | ||
*/ | ||
readFile(options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding): Promise<string>; | ||
readFile( | ||
options: | ||
| { | ||
encoding: BufferEncoding; | ||
flag?: OpenMode | undefined; | ||
} | ||
| BufferEncoding, | ||
): Promise<string>; | ||
/** | ||
@@ -91,191 +301,321 @@ * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. | ||
*/ | ||
readFile(options?: BaseEncodingOptions & { flag?: OpenMode } | BufferEncoding | null): Promise<string | Buffer>; | ||
readFile( | ||
options?: | ||
| (ObjectEncodingOptions & { | ||
flag?: OpenMode | undefined; | ||
}) | ||
| BufferEncoding | ||
| null, | ||
): Promise<string | Buffer>; | ||
/** | ||
* Asynchronous fstat(2) - Get file status. | ||
* Convenience method to create a `readline` interface and stream over the file. | ||
* See `filehandle.createReadStream()` for the options. | ||
* | ||
* ```js | ||
* import { open } from 'node:fs/promises'; | ||
* | ||
* const file = await open('./some/file/to/read'); | ||
* | ||
* for await (const line of file.readLines()) { | ||
* console.log(line); | ||
* } | ||
* ``` | ||
* @since v18.11.0 | ||
*/ | ||
stat(): Promise<Stats>; | ||
readLines(options?: CreateReadStreamOptions): ReadlineInterface; | ||
/** | ||
* Asynchronous ftruncate(2) - Truncate a file to a specified length. | ||
* @param len If not specified, defaults to `0`. | ||
* @since v10.0.0 | ||
* @return Fulfills with an {fs.Stats} for the file. | ||
*/ | ||
stat( | ||
opts?: StatOptions & { | ||
bigint?: false | undefined; | ||
}, | ||
): Promise<Stats>; | ||
stat( | ||
opts: StatOptions & { | ||
bigint: true; | ||
}, | ||
): Promise<BigIntStats>; | ||
stat(opts?: StatOptions): Promise<Stats | BigIntStats>; | ||
/** | ||
* Truncates the file. | ||
* | ||
* If the file was larger than `len` bytes, only the first `len` bytes will be | ||
* retained in the file. | ||
* | ||
* The following example retains only the first four bytes of the file: | ||
* | ||
* ```js | ||
* import { open } from 'node:fs/promises'; | ||
* | ||
* let filehandle = null; | ||
* try { | ||
* filehandle = await open('temp.txt', 'r+'); | ||
* await filehandle.truncate(4); | ||
* } finally { | ||
* await filehandle?.close(); | ||
* } | ||
* ``` | ||
* | ||
* If the file previously was shorter than `len` bytes, it is extended, and the | ||
* extended part is filled with null bytes (`'\0'`): | ||
* | ||
* If `len` is negative then `0` will be used. | ||
* @since v10.0.0 | ||
* @param [len=0] | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
truncate(len?: number): Promise<void>; | ||
/** | ||
* Asynchronously change file timestamps of the file. | ||
* @param atime The last access time. If a string is provided, it will be coerced to number. | ||
* @param mtime The last modified time. If a string is provided, it will be coerced to number. | ||
* Change the file system timestamps of the object referenced by the `FileHandle` then resolves the promise with no arguments upon success. | ||
* @since v10.0.0 | ||
*/ | ||
utimes(atime: string | number | Date, mtime: string | number | Date): Promise<void>; | ||
utimes(atime: TimeLike, mtime: TimeLike): Promise<void>; | ||
/** | ||
* Asynchronously writes `buffer` to the file. | ||
* The `FileHandle` must have been opened for writing. | ||
* @param buffer The buffer that the data will be written to. | ||
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`. | ||
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. | ||
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. | ||
* Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an | ||
* [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an | ||
* [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. | ||
* The promise is resolved with no arguments upon success. | ||
* | ||
* If `options` is a string, then it specifies the `encoding`. | ||
* | ||
* The `FileHandle` has to support writing. | ||
* | ||
* It is unsafe to use `filehandle.writeFile()` multiple times on the same file | ||
* without waiting for the promise to be resolved (or rejected). | ||
* | ||
* If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the | ||
* current position till the end of the file. It doesn't always write from the | ||
* beginning of the file. | ||
* @since v10.0.0 | ||
*/ | ||
write<TBuffer extends Uint8Array>(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; | ||
writeFile( | ||
data: string | Uint8Array, | ||
options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null, | ||
): Promise<void>; | ||
/** | ||
* Asynchronously writes `string` to the file. | ||
* The `FileHandle` must have been opened for writing. | ||
* It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` | ||
* to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. | ||
* @param string A string to write. | ||
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. | ||
* @param encoding The expected string encoding. | ||
* Write `buffer` to the file. | ||
* | ||
* The promise is resolved with an object containing two properties: | ||
* | ||
* It is unsafe to use `filehandle.write()` multiple times on the same file | ||
* without waiting for the promise to be resolved (or rejected). For this | ||
* scenario, use `filehandle.createWriteStream()`. | ||
* | ||
* On Linux, positional writes do not work when the file is opened in append mode. | ||
* The kernel ignores the position argument and always appends the data to | ||
* the end of the file. | ||
* @since v10.0.0 | ||
* @param offset The start position from within `buffer` where the data to write begins. | ||
* @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. | ||
* @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current | ||
* position. See the POSIX pwrite(2) documentation for more detail. | ||
*/ | ||
write(data: string | Uint8Array, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; | ||
write<TBuffer extends Uint8Array>( | ||
buffer: TBuffer, | ||
offset?: number | null, | ||
length?: number | null, | ||
position?: number | null, | ||
): Promise<{ | ||
bytesWritten: number; | ||
buffer: TBuffer; | ||
}>; | ||
write( | ||
data: string, | ||
position?: number | null, | ||
encoding?: BufferEncoding | null, | ||
): Promise<{ | ||
bytesWritten: number; | ||
buffer: string; | ||
}>; | ||
/** | ||
* Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. | ||
* The `FileHandle` must have been opened for writing. | ||
* It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). | ||
* @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. | ||
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. | ||
* If `encoding` is not supplied, the default of `'utf8'` is used. | ||
* If `mode` is not supplied, the default of `0o666` is used. | ||
* If `mode` is a string, it is parsed as an octal integer. | ||
* If `flag` is not supplied, the default of `'w'` is used. | ||
* Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. | ||
* | ||
* The promise is resolved with an object containing a two properties: | ||
* | ||
* It is unsafe to call `writev()` multiple times on the same file without waiting | ||
* for the promise to be resolved (or rejected). | ||
* | ||
* On Linux, positional writes don't work when the file is opened in append mode. | ||
* The kernel ignores the position argument and always appends the data to | ||
* the end of the file. | ||
* @since v12.9.0 | ||
* @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current | ||
* position. | ||
*/ | ||
writeFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise<void>; | ||
writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise<WriteVResult>; | ||
/** | ||
* See `fs.writev` promisified version. | ||
* Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s | ||
* @since v13.13.0, v12.17.0 | ||
* @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. | ||
* @return Fulfills upon success an object containing two properties: | ||
*/ | ||
writev(buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): Promise<WriteVResult>; | ||
readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise<ReadVResult>; | ||
/** | ||
* See `fs.readv` promisified version. | ||
* Closes the file handle after waiting for any pending operation on the handle to | ||
* complete. | ||
* | ||
* ```js | ||
* import { open } from 'node:fs/promises'; | ||
* | ||
* let filehandle; | ||
* try { | ||
* filehandle = await open('thefile.txt', 'r'); | ||
* } finally { | ||
* await filehandle?.close(); | ||
* } | ||
* ``` | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
readv(buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): Promise<ReadVResult>; | ||
close(): Promise<void>; | ||
/** | ||
* Asynchronous close(2) - close a `FileHandle`. | ||
* An alias for {@link FileHandle.close()}. | ||
* @since v20.4.0 | ||
*/ | ||
close(): Promise<void>; | ||
[Symbol.asyncDispose](): Promise<void>; | ||
} | ||
const constants: typeof fsConstants; | ||
/** | ||
* Asynchronously tests a user's permissions for the file specified by path. | ||
* @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. | ||
* URL support is _experimental_. | ||
* Tests a user's permissions for the file or directory specified by `path`. | ||
* The `mode` argument is an optional integer that specifies the accessibility | ||
* checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` | ||
* (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for | ||
* possible values of `mode`. | ||
* | ||
* If the accessibility check is successful, the promise is resolved with no | ||
* value. If any of the accessibility checks fail, the promise is rejected | ||
* with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and | ||
* written by the current process. | ||
* | ||
* ```js | ||
* import { access, constants } from 'node:fs/promises'; | ||
* | ||
* try { | ||
* await access('/etc/passwd', constants.R_OK | constants.W_OK); | ||
* console.log('can access'); | ||
* } catch { | ||
* console.error('cannot access'); | ||
* } | ||
* ``` | ||
* | ||
* Using `fsPromises.access()` to check for the accessibility of a file before | ||
* calling `fsPromises.open()` is not recommended. Doing so introduces a race | ||
* condition, since other processes may change the file's state between the two | ||
* calls. Instead, user code should open/read/write the file directly and handle | ||
* the error raised if the file is not accessible. | ||
* @since v10.0.0 | ||
* @param [mode=fs.constants.F_OK] | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function access(path: PathLike, mode?: number): Promise<void>; | ||
/** | ||
* Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. | ||
* Node.js makes no guarantees about the atomicity of the copy operation. | ||
* If an error occurs after the destination file has been opened for writing, Node.js will attempt | ||
* to remove the destination. | ||
* @param src A path to the source file. | ||
* @param dest A path to the destination file. | ||
* @param flags An optional integer that specifies the behavior of the copy operation. The only | ||
* supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if | ||
* `dest` already exists. | ||
* Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it | ||
* already exists. | ||
* | ||
* No guarantees are made about the atomicity of the copy operation. If an | ||
* error occurs after the destination file has been opened for writing, an attempt | ||
* will be made to remove the destination. | ||
* | ||
* ```js | ||
* import { copyFile, constants } from 'node:fs/promises'; | ||
* | ||
* try { | ||
* await copyFile('source.txt', 'destination.txt'); | ||
* console.log('source.txt was copied to destination.txt'); | ||
* } catch { | ||
* console.error('The file could not be copied'); | ||
* } | ||
* | ||
* // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. | ||
* try { | ||
* await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); | ||
* console.log('source.txt was copied to destination.txt'); | ||
* } catch { | ||
* console.error('The file could not be copied'); | ||
* } | ||
* ``` | ||
* @since v10.0.0 | ||
* @param src source filename to copy | ||
* @param dest destination filename of the copy operation | ||
* @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. | ||
* `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise<void>; | ||
function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise<void>; | ||
/** | ||
* Asynchronous open(2) - open and possibly create a file. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not | ||
* supplied, defaults to `0o666`. | ||
* Opens a `FileHandle`. | ||
* | ||
* Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. | ||
* | ||
* Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented | ||
* by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains | ||
* a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). | ||
* @since v10.0.0 | ||
* @param [flags='r'] See `support of file system `flags``. | ||
* @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. | ||
* @return Fulfills with a {FileHandle} object. | ||
*/ | ||
function open(path: PathLike, flags: string | number, mode?: Mode): Promise<FileHandle>; | ||
function open(path: PathLike, flags?: string | number, mode?: Mode): Promise<FileHandle>; | ||
/** | ||
* Asynchronously reads data from the file referenced by the supplied `FileHandle`. | ||
* @param handle A `FileHandle`. | ||
* @param buffer The buffer that the data will be written to. | ||
* @param offset The offset in the buffer at which to start writing. | ||
* @param length The number of bytes to read. | ||
* @param position The offset from the beginning of the file from which data should be read. If | ||
* `null`, data will be read from the current position. | ||
* Renames `oldPath` to `newPath`. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function read<TBuffer extends Uint8Array>( | ||
handle: FileHandle, | ||
buffer: TBuffer, | ||
offset?: number | null, | ||
length?: number | null, | ||
position?: number | null, | ||
): Promise<{ bytesRead: number, buffer: TBuffer }>; | ||
/** | ||
* Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. | ||
* It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` | ||
* to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. | ||
* @param handle A `FileHandle`. | ||
* @param buffer The buffer that the data will be written to. | ||
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`. | ||
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. | ||
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. | ||
*/ | ||
function write<TBuffer extends Uint8Array>( | ||
handle: FileHandle, | ||
buffer: TBuffer, | ||
offset?: number | null, | ||
length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; | ||
/** | ||
* Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. | ||
* It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` | ||
* to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. | ||
* @param handle A `FileHandle`. | ||
* @param string A string to write. | ||
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. | ||
* @param encoding The expected string encoding. | ||
*/ | ||
function write(handle: FileHandle, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; | ||
/** | ||
* Asynchronous rename(2) - Change the name or location of a file or directory. | ||
* @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* URL support is _experimental_. | ||
* @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* URL support is _experimental_. | ||
*/ | ||
function rename(oldPath: PathLike, newPath: PathLike): Promise<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. | ||
* @param len If not specified, defaults to `0`. | ||
* Truncates (shortens or extends the length) of the content at `path` to `len`bytes. | ||
* @since v10.0.0 | ||
* @param [len=0] | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function truncate(path: PathLike, len?: number): Promise<void>; | ||
/** | ||
* Asynchronous ftruncate(2) - Truncate a file to a specified length. | ||
* @param handle A `FileHandle`. | ||
* @param len If not specified, defaults to `0`. | ||
* Removes the directory identified by `path`. | ||
* | ||
* Using `fsPromises.rmdir()` on a file (not a directory) results in the | ||
* promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. | ||
* | ||
* To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function ftruncate(handle: FileHandle, len?: number): Promise<void>; | ||
/** | ||
* Asynchronous rmdir(2) - delete a directory. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
*/ | ||
function rmdir(path: PathLike, options?: RmDirOptions): Promise<void>; | ||
/** | ||
* Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). | ||
* Removes files and directories (modeled on the standard POSIX `rm` utility). | ||
* @since v14.14.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function rm(path: PathLike, options?: RmOptions): Promise<void>; | ||
/** | ||
* Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. | ||
* @param handle A `FileHandle`. | ||
* Asynchronously creates a directory. | ||
* | ||
* The optional `options` argument can be an integer specifying `mode` (permission | ||
* and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory | ||
* that exists results in a | ||
* rejection only when `recursive` is false. | ||
* | ||
* ```js | ||
* import { mkdir } from 'node:fs/promises'; | ||
* | ||
* try { | ||
* const projectFolder = new URL('./test/project/', import.meta.url); | ||
* const createDir = await mkdir(projectFolder, { recursive: true }); | ||
* | ||
* console.log(`created ${createDir}`); | ||
* } catch (err) { | ||
* console.error(err.message); | ||
* } | ||
* ``` | ||
* @since v10.0.0 | ||
* @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. | ||
*/ | ||
function fdatasync(handle: FileHandle): Promise<void>; | ||
function mkdir( | ||
path: PathLike, | ||
options: MakeDirectoryOptions & { | ||
recursive: true; | ||
}, | ||
): Promise<string | undefined>; | ||
/** | ||
* Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. | ||
* @param handle A `FileHandle`. | ||
*/ | ||
function fsync(handle: FileHandle): Promise<void>; | ||
/** | ||
* Asynchronous mkdir(2) - create a directory. | ||
@@ -286,4 +626,11 @@ * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
*/ | ||
function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise<string>; | ||
function mkdir( | ||
path: PathLike, | ||
options?: | ||
| Mode | ||
| (MakeDirectoryOptions & { | ||
recursive?: false | undefined; | ||
}) | ||
| null, | ||
): Promise<void>; | ||
/** | ||
@@ -295,19 +642,37 @@ * Asynchronous mkdir(2) - create a directory. | ||
*/ | ||
function mkdir(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise<void>; | ||
/** | ||
* Asynchronous mkdir(2) - create a directory. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders | ||
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. | ||
*/ | ||
function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise<string | undefined>; | ||
/** | ||
* 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 The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. | ||
* Reads the contents of a directory. | ||
* | ||
* The optional `options` argument can be a string specifying an encoding, or an | ||
* object with an `encoding` property specifying the character encoding to use for | ||
* the filenames. If the `encoding` is set to `'buffer'`, the filenames returned | ||
* will be passed as `Buffer` objects. | ||
* | ||
* If `options.withFileTypes` is set to `true`, the resolved array will contain `fs.Dirent` objects. | ||
* | ||
* ```js | ||
* import { readdir } from 'node:fs/promises'; | ||
* | ||
* try { | ||
* const files = await readdir(path); | ||
* for (const file of files) | ||
* console.log(file); | ||
* } catch (err) { | ||
* console.error(err); | ||
* } | ||
* ``` | ||
* @since v10.0.0 | ||
* @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. | ||
*/ | ||
function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise<string[]>; | ||
function readdir( | ||
path: PathLike, | ||
options?: | ||
| (ObjectEncodingOptions & { | ||
withFileTypes?: false | undefined; | ||
recursive?: boolean | undefined; | ||
}) | ||
| BufferEncoding | ||
| null, | ||
): Promise<string[]>; | ||
/** | ||
@@ -318,4 +683,12 @@ * Asynchronous readdir(3) - read a directory. | ||
*/ | ||
function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise<Buffer[]>; | ||
function readdir( | ||
path: PathLike, | ||
options: | ||
| { | ||
encoding: "buffer"; | ||
withFileTypes?: false | undefined; | ||
recursive?: boolean | undefined; | ||
} | ||
| "buffer", | ||
): Promise<Buffer[]>; | ||
/** | ||
@@ -326,4 +699,12 @@ * Asynchronous readdir(3) - read a directory. | ||
*/ | ||
function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise<string[] | Buffer[]>; | ||
function readdir( | ||
path: PathLike, | ||
options?: | ||
| (ObjectEncodingOptions & { | ||
withFileTypes?: false | undefined; | ||
recursive?: boolean | undefined; | ||
}) | ||
| BufferEncoding | ||
| null, | ||
): Promise<string[] | Buffer[]>; | ||
/** | ||
@@ -334,11 +715,21 @@ * Asynchronous readdir(3) - read a directory. | ||
*/ | ||
function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise<Dirent[]>; | ||
function readdir( | ||
path: PathLike, | ||
options: ObjectEncodingOptions & { | ||
withFileTypes: true; | ||
recursive?: boolean | undefined; | ||
}, | ||
): Promise<Dirent[]>; | ||
/** | ||
* Asynchronous readlink(2) - read value of a symbolic link. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. | ||
* 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 | ||
* resolved with the`linkString` upon success. | ||
* | ||
* The optional `options` argument can be a string specifying an encoding, or an | ||
* object with an `encoding` property specifying the character encoding to use for | ||
* the link path returned. If the `encoding` is set to `'buffer'`, the link path | ||
* returned will be passed as a `Buffer` object. | ||
* @since v10.0.0 | ||
* @return Fulfills with the `linkString` upon success. | ||
*/ | ||
function readlink(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise<string>; | ||
function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>; | ||
/** | ||
@@ -350,3 +741,2 @@ * Asynchronous readlink(2) - read value of a symbolic link. | ||
function readlink(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; | ||
/** | ||
@@ -357,109 +747,148 @@ * Asynchronous readlink(2) - read value of a symbolic link. | ||
*/ | ||
function readlink(path: PathLike, options?: BaseEncodingOptions | string | null): Promise<string | Buffer>; | ||
function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise<string | Buffer>; | ||
/** | ||
* Asynchronous symlink(2) - Create a new symbolic link to an existing file. | ||
* @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. | ||
* @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. | ||
* @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). | ||
* When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. | ||
* Creates a symbolic link. | ||
* | ||
* The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will | ||
* autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not | ||
* exist, `'file'` will be used. Windows junction points require the destination | ||
* path to be absolute. When using `'junction'`, the `target` argument will | ||
* automatically be normalized to absolute path. Junction points on NTFS volumes | ||
* can only point to directories. | ||
* @since v10.0.0 | ||
* @param [type='null'] | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function symlink(target: PathLike, path: PathLike, type?: string | null): Promise<void>; | ||
/** | ||
* Asynchronous fstat(2) - Get file status. | ||
* @param handle A `FileHandle`. | ||
* Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, | ||
* in which case the link itself is stat-ed, not the file that it refers to. | ||
* Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. | ||
* @since v10.0.0 | ||
* @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. | ||
*/ | ||
function fstat(handle: FileHandle): Promise<Stats>; | ||
function lstat( | ||
path: PathLike, | ||
opts?: StatOptions & { | ||
bigint?: false | undefined; | ||
}, | ||
): Promise<Stats>; | ||
function lstat( | ||
path: PathLike, | ||
opts: StatOptions & { | ||
bigint: true; | ||
}, | ||
): Promise<BigIntStats>; | ||
function lstat(path: PathLike, opts?: StatOptions): Promise<Stats | BigIntStats>; | ||
/** | ||
* Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @since v10.0.0 | ||
* @return Fulfills with the {fs.Stats} object for the given `path`. | ||
*/ | ||
function lstat(path: PathLike): Promise<Stats>; | ||
function stat( | ||
path: PathLike, | ||
opts?: StatOptions & { | ||
bigint?: false | undefined; | ||
}, | ||
): Promise<Stats>; | ||
function stat( | ||
path: PathLike, | ||
opts: StatOptions & { | ||
bigint: true; | ||
}, | ||
): Promise<BigIntStats>; | ||
function stat(path: PathLike, opts?: StatOptions): Promise<Stats | BigIntStats>; | ||
/** | ||
* Asynchronous stat(2) - Get file status. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @since v19.6.0, v18.15.0 | ||
* @return Fulfills with the {fs.StatFs} object for the given `path`. | ||
*/ | ||
function stat(path: PathLike): Promise<Stats>; | ||
function statfs( | ||
path: PathLike, | ||
opts?: StatFsOptions & { | ||
bigint?: false | undefined; | ||
}, | ||
): Promise<StatsFs>; | ||
function statfs( | ||
path: PathLike, | ||
opts: StatFsOptions & { | ||
bigint: true; | ||
}, | ||
): Promise<BigIntStatsFs>; | ||
function statfs(path: PathLike, opts?: StatFsOptions): Promise<StatsFs | BigIntStatsFs>; | ||
/** | ||
* Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. | ||
* @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function link(existingPath: PathLike, newPath: PathLike): Promise<void>; | ||
/** | ||
* Asynchronous unlink(2) - delete a name and possibly the file it refers to. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* If `path` refers to a symbolic link, then the link is removed without affecting | ||
* the file or directory to which that link refers. If the `path` refers to a file | ||
* path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function unlink(path: PathLike): Promise<void>; | ||
/** | ||
* Asynchronous fchmod(2) - Change permissions of a file. | ||
* @param handle A `FileHandle`. | ||
* @param mode A file mode. If a string is passed, it is parsed as an octal integer. | ||
* Changes the permissions of a file. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function fchmod(handle: FileHandle, mode: Mode): Promise<void>; | ||
/** | ||
* Asynchronous chmod(2) - Change permissions of a file. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param mode A file mode. If a string is passed, it is parsed as an octal integer. | ||
*/ | ||
function chmod(path: PathLike, mode: Mode): Promise<void>; | ||
/** | ||
* Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param mode A file mode. If a string is passed, it is parsed as an octal integer. | ||
* Changes the permissions on a symbolic link. | ||
* | ||
* This method is only implemented on macOS. | ||
* @deprecated Since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function lchmod(path: PathLike, mode: Mode): Promise<void>; | ||
/** | ||
* Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* Changes the ownership on a symbolic link. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function lchown(path: PathLike, uid: number, gid: number): Promise<void>; | ||
/** | ||
* Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, | ||
* with the difference that if the path refers to a symbolic link, then the link is not | ||
* dereferenced: instead, the timestamps of the symbolic link itself are changed. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param atime The last access time. If a string is provided, it will be coerced to number. | ||
* @param mtime The last modified time. If a string is provided, it will be coerced to number. | ||
* Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a | ||
* symbolic link, then the link is not dereferenced: instead, the timestamps of | ||
* the symbolic link itself are changed. | ||
* @since v14.5.0, v12.19.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>; | ||
function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>; | ||
/** | ||
* Asynchronous fchown(2) - Change ownership of a file. | ||
* @param handle A `FileHandle`. | ||
* Changes the ownership of a file. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function fchown(handle: FileHandle, uid: number, gid: number): Promise<void>; | ||
/** | ||
* Asynchronous chown(2) - Change ownership of a file. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
*/ | ||
function chown(path: PathLike, uid: number, gid: number): Promise<void>; | ||
/** | ||
* Asynchronously change file timestamps of the file referenced by the supplied path. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param atime The last access time. If a string is provided, it will be coerced to number. | ||
* @param mtime The last modified time. If a string is provided, it will be coerced to number. | ||
* Change the file system timestamps of the object referenced by `path`. | ||
* | ||
* The `atime` and `mtime` arguments follow these rules: | ||
* | ||
* * Values can be either numbers representing Unix epoch time, `Date`s, or a | ||
* numeric string like `'123456789.0'`. | ||
* * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. | ||
* @since v10.0.0 | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>; | ||
function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>; | ||
/** | ||
* Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. | ||
* @param handle A `FileHandle`. | ||
* @param atime The last access time. If a string is provided, it will be coerced to number. | ||
* @param mtime The last modified time. If a string is provided, it will be coerced to number. | ||
* Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. | ||
* | ||
* Only paths that can be converted to UTF8 strings are supported. | ||
* | ||
* The optional `options` argument can be a string specifying an encoding, or an | ||
* object with an `encoding` property specifying the character encoding to use for | ||
* the path. If the `encoding` is set to `'buffer'`, the path returned will be | ||
* passed as a `Buffer` object. | ||
* | ||
* On Linux, when Node.js is linked against musl libc, the procfs file system must | ||
* be mounted on `/proc` in order for this function to work. Glibc does not have | ||
* this restriction. | ||
* @since v10.0.0 | ||
* @return Fulfills with the resolved path upon success. | ||
*/ | ||
function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise<void>; | ||
function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>; | ||
/** | ||
@@ -470,11 +899,3 @@ * Asynchronous realpath(3) - return the canonicalized absolute pathname. | ||
*/ | ||
function realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise<string>; | ||
/** | ||
* Asynchronous realpath(3) - return the canonicalized absolute pathname. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. | ||
*/ | ||
function realpath(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; | ||
/** | ||
@@ -485,11 +906,36 @@ * Asynchronous realpath(3) - return the canonicalized absolute pathname. | ||
*/ | ||
function realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise<string | Buffer>; | ||
function realpath( | ||
path: PathLike, | ||
options?: ObjectEncodingOptions | BufferEncoding | null, | ||
): Promise<string | Buffer>; | ||
/** | ||
* Asynchronously creates a unique temporary directory. | ||
* Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. | ||
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. | ||
* Creates a unique temporary directory. A unique directory name is generated by | ||
* appending six random characters to the end of the provided `prefix`. Due to | ||
* platform inconsistencies, avoid trailing `X` characters in `prefix`. Some | ||
* platforms, notably the BSDs, can return more than six random characters, and | ||
* replace trailing `X` characters in `prefix` with random characters. | ||
* | ||
* The optional `options` argument can be a string specifying an encoding, or an | ||
* object with an `encoding` property specifying the character encoding to use. | ||
* | ||
* ```js | ||
* import { mkdtemp } from 'node:fs/promises'; | ||
* import { join } from 'node:path'; | ||
* import { tmpdir } from 'node:os'; | ||
* | ||
* try { | ||
* await mkdtemp(join(tmpdir(), 'foo-')); | ||
* } catch (err) { | ||
* console.error(err); | ||
* } | ||
* ``` | ||
* | ||
* 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`). | ||
* @since v10.0.0 | ||
* @return Fulfills with a string containing the file system path of the newly created temporary directory. | ||
*/ | ||
function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise<string>; | ||
function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string>; | ||
/** | ||
@@ -501,3 +947,2 @@ * Asynchronously creates a unique temporary directory. | ||
function mkdtemp(prefix: string, options: BufferEncodingOption): Promise<Buffer>; | ||
/** | ||
@@ -508,42 +953,153 @@ * Asynchronously creates a unique temporary directory. | ||
*/ | ||
function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise<string | Buffer>; | ||
function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string | Buffer>; | ||
/** | ||
* Asynchronously writes data to a file, replacing the file if it already exists. | ||
* It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* URL support is _experimental_. | ||
* If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. | ||
* @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. | ||
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. | ||
* If `encoding` is not supplied, the default of `'utf8'` is used. | ||
* If `mode` is not supplied, the default of `0o666` is used. | ||
* If `mode` is a string, it is parsed as an octal integer. | ||
* If `flag` is not supplied, the default of `'w'` is used. | ||
* Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an | ||
* [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an | ||
* [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. | ||
* | ||
* The `encoding` option is ignored if `data` is a buffer. | ||
* | ||
* If `options` is a string, then it specifies the encoding. | ||
* | ||
* The `mode` option only affects the newly created file. See `fs.open()` for more details. | ||
* | ||
* Any specified `FileHandle` has to support writing. | ||
* | ||
* It is unsafe to use `fsPromises.writeFile()` multiple times on the same file | ||
* without waiting for the promise to be settled. | ||
* | ||
* Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience | ||
* method that performs multiple `write` calls internally to write the buffer | ||
* passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. | ||
* | ||
* It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. | ||
* Cancelation is "best effort", and some amount of data is likely still | ||
* to be written. | ||
* | ||
* ```js | ||
* import { writeFile } from 'node:fs/promises'; | ||
* import { Buffer } from 'node:buffer'; | ||
* | ||
* try { | ||
* const controller = new AbortController(); | ||
* const { signal } = controller; | ||
* const data = new Uint8Array(Buffer.from('Hello Node.js')); | ||
* const promise = writeFile('message.txt', data, { signal }); | ||
* | ||
* // Abort the request before the promise settles. | ||
* controller.abort(); | ||
* | ||
* await promise; | ||
* } catch (err) { | ||
* // When a request is aborted - err is an AbortError | ||
* console.error(err); | ||
* } | ||
* ``` | ||
* | ||
* Aborting an ongoing request does not abort individual operating | ||
* system requests but rather the internal buffering `fs.writeFile` performs. | ||
* @since v10.0.0 | ||
* @param file filename or `FileHandle` | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function writeFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise<void>; | ||
function writeFile( | ||
file: PathLike | FileHandle, | ||
data: | ||
| string | ||
| NodeJS.ArrayBufferView | ||
| Iterable<string | NodeJS.ArrayBufferView> | ||
| AsyncIterable<string | NodeJS.ArrayBufferView> | ||
| Stream, | ||
options?: | ||
| (ObjectEncodingOptions & { | ||
mode?: Mode | undefined; | ||
flag?: OpenMode | undefined; | ||
} & Abortable) | ||
| BufferEncoding | ||
| null, | ||
): Promise<void>; | ||
/** | ||
* Asynchronously append data to a file, creating the file if it does not exist. | ||
* @param file A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* URL support is _experimental_. | ||
* If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. | ||
* @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. | ||
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. | ||
* If `encoding` is not supplied, the default of `'utf8'` is used. | ||
* If `mode` is not supplied, the default of `0o666` is used. | ||
* If `mode` is a string, it is parsed as an octal integer. | ||
* If `flag` is not supplied, the default of `'a'` is used. | ||
* Asynchronously append data to a file, creating the file if it does not yet | ||
* exist. `data` can be a string or a `Buffer`. | ||
* | ||
* If `options` is a string, then it specifies the `encoding`. | ||
* | ||
* The `mode` option only affects the newly created file. See `fs.open()` for more details. | ||
* | ||
* The `path` may be specified as a `FileHandle` that has been opened | ||
* for appending (using `fsPromises.open()`). | ||
* @since v10.0.0 | ||
* @param path filename or {FileHandle} | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise<void>; | ||
function appendFile( | ||
path: PathLike | FileHandle, | ||
data: string | Uint8Array, | ||
options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null, | ||
): Promise<void>; | ||
/** | ||
* Asynchronously reads the entire contents of a file. | ||
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. | ||
* If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. | ||
* @param options An object that may contain an optional flag. | ||
* If a flag is not provided, it defaults to `'r'`. | ||
* | ||
* If no encoding is specified (using `options.encoding`), the data is returned | ||
* as a `Buffer` object. Otherwise, the data will be a string. | ||
* | ||
* If `options` is a string, then it specifies the encoding. | ||
* | ||
* When the `path` is a directory, the behavior of `fsPromises.readFile()` is | ||
* platform-specific. On macOS, Linux, and Windows, the promise will be rejected | ||
* with an error. On FreeBSD, a representation of the directory's contents will be | ||
* returned. | ||
* | ||
* An example of reading a `package.json` file located in the same directory of the | ||
* running code: | ||
* | ||
* ```js | ||
* import { readFile } from 'node:fs/promises'; | ||
* try { | ||
* const filePath = new URL('./package.json', import.meta.url); | ||
* const contents = await readFile(filePath, { encoding: 'utf8' }); | ||
* console.log(contents); | ||
* } catch (err) { | ||
* console.error(err.message); | ||
* } | ||
* ``` | ||
* | ||
* It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a | ||
* request is aborted the promise returned is rejected with an `AbortError`: | ||
* | ||
* ```js | ||
* import { readFile } from 'node:fs/promises'; | ||
* | ||
* try { | ||
* const controller = new AbortController(); | ||
* const { signal } = controller; | ||
* const promise = readFile(fileName, { signal }); | ||
* | ||
* // Abort the request before the promise settles. | ||
* controller.abort(); | ||
* | ||
* await promise; | ||
* } catch (err) { | ||
* // When a request is aborted - err is an AbortError | ||
* console.error(err); | ||
* } | ||
* ``` | ||
* | ||
* Aborting an ongoing request does not abort individual operating | ||
* system requests but rather the internal buffering `fs.readFile` performs. | ||
* | ||
* Any specified `FileHandle` has to support reading. | ||
* @since v10.0.0 | ||
* @param path filename or `FileHandle` | ||
* @return Fulfills with the contents of the file. | ||
*/ | ||
function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: OpenMode } | null): Promise<Buffer>; | ||
function readFile( | ||
path: PathLike | FileHandle, | ||
options?: | ||
| ({ | ||
encoding?: null | undefined; | ||
flag?: OpenMode | undefined; | ||
} & Abortable) | ||
| null, | ||
): Promise<Buffer>; | ||
/** | ||
@@ -556,4 +1112,11 @@ * Asynchronously reads the entire contents of a file. | ||
*/ | ||
function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding): Promise<string>; | ||
function readFile( | ||
path: PathLike | FileHandle, | ||
options: | ||
| ({ | ||
encoding: BufferEncoding; | ||
flag?: OpenMode | undefined; | ||
} & Abortable) | ||
| BufferEncoding, | ||
): Promise<string>; | ||
/** | ||
@@ -566,5 +1129,119 @@ * Asynchronously reads the entire contents of a file. | ||
*/ | ||
function readFile(path: PathLike | FileHandle, options?: BaseEncodingOptions & { flag?: OpenMode } | BufferEncoding | null): Promise<string | Buffer>; | ||
function opendir(path: string, options?: OpenDirOptions): Promise<Dir>; | ||
function readFile( | ||
path: PathLike | FileHandle, | ||
options?: | ||
| ( | ||
& ObjectEncodingOptions | ||
& Abortable | ||
& { | ||
flag?: OpenMode | undefined; | ||
} | ||
) | ||
| BufferEncoding | ||
| null, | ||
): Promise<string | Buffer>; | ||
/** | ||
* Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. | ||
* | ||
* Creates an `fs.Dir`, which contains all further functions for reading from | ||
* and cleaning up the directory. | ||
* | ||
* The `encoding` option sets the encoding for the `path` while opening the | ||
* directory and subsequent read operations. | ||
* | ||
* Example using async iteration: | ||
* | ||
* ```js | ||
* import { opendir } from 'node:fs/promises'; | ||
* | ||
* try { | ||
* const dir = await opendir('./'); | ||
* for await (const dirent of dir) | ||
* console.log(dirent.name); | ||
* } catch (err) { | ||
* console.error(err); | ||
* } | ||
* ``` | ||
* | ||
* When using the async iterator, the `fs.Dir` object will be automatically | ||
* closed after the iterator exits. | ||
* @since v12.12.0 | ||
* @return Fulfills with an {fs.Dir}. | ||
*/ | ||
function opendir(path: PathLike, options?: OpenDirOptions): Promise<Dir>; | ||
/** | ||
* 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'); | ||
* | ||
* const ac = new AbortController(); | ||
* const { signal } = ac; | ||
* setTimeout(() => ac.abort(), 10000); | ||
* | ||
* (async () => { | ||
* try { | ||
* const watcher = watch(__filename, { signal }); | ||
* for await (const event of watcher) | ||
* console.log(event); | ||
* } catch (err) { | ||
* if (err.name === 'AbortError') | ||
* return; | ||
* throw err; | ||
* } | ||
* })(); | ||
* ``` | ||
* | ||
* On most platforms, `'rename'` is emitted whenever a filename appears or | ||
* disappears in the directory. | ||
* | ||
* All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. | ||
* @since v15.9.0, v14.18.0 | ||
* @return of objects with the properties: | ||
*/ | ||
function watch( | ||
filename: PathLike, | ||
options: | ||
| (WatchOptions & { | ||
encoding: "buffer"; | ||
}) | ||
| "buffer", | ||
): AsyncIterable<FileChangeInfo<Buffer>>; | ||
/** | ||
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. | ||
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. | ||
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. | ||
* If `encoding` is not supplied, the default of `'utf8'` is used. | ||
* If `persistent` is not supplied, the default of `true` is used. | ||
* If `recursive` is not supplied, the default of `false` is used. | ||
*/ | ||
function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable<FileChangeInfo<string>>; | ||
/** | ||
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. | ||
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. | ||
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. | ||
* If `encoding` is not supplied, the default of `'utf8'` is used. | ||
* If `persistent` is not supplied, the default of `true` is used. | ||
* If `recursive` is not supplied, the default of `false` is used. | ||
*/ | ||
function watch( | ||
filename: PathLike, | ||
options: WatchOptions | string, | ||
): AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>>; | ||
/** | ||
* Asynchronously copies the entire directory structure from `src` to `dest`, | ||
* including subdirectories and files. | ||
* | ||
* When copying a directory to another directory, globs are not supported and | ||
* behavior is similar to `cp dir1/ dir2/`. | ||
* @since v16.7.0 | ||
* @experimental | ||
* @param src source path to copy. | ||
* @param dest destination path to copy to. | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise<void>; | ||
} | ||
declare module "node:fs/promises" { | ||
export * from "fs/promises"; | ||
} |
@@ -9,5 +9,5 @@ // Declare "static" methods in Error | ||
* | ||
* @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces | ||
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces | ||
*/ | ||
prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; | ||
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; | ||
@@ -17,19 +17,2 @@ stackTraceLimit: number; | ||
// Node.js ESNEXT support | ||
interface String { | ||
/** Removes whitespace from the left end of a string. */ | ||
trimLeft(): string; | ||
/** Removes whitespace from the right end of a string. */ | ||
trimRight(): string; | ||
/** Returns a copy with leading whitespace removed. */ | ||
trimStart(): string; | ||
/** Returns a copy with trailing whitespace removed. */ | ||
trimEnd(): string; | ||
} | ||
interface ImportMeta { | ||
url: string; | ||
} | ||
/*-----------------------------------------------* | ||
@@ -52,19 +35,2 @@ * * | ||
declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; | ||
declare namespace setTimeout { | ||
function __promisify__(ms: number): Promise<void>; | ||
function __promisify__<T>(ms: number, value: T): Promise<T>; | ||
} | ||
declare function clearTimeout(timeoutId: NodeJS.Timeout): void; | ||
declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; | ||
declare function clearInterval(intervalId: NodeJS.Timeout): void; | ||
declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; | ||
declare namespace setImmediate { | ||
function __promisify__(): Promise<void>; | ||
function __promisify__<T>(value: T): Promise<T>; | ||
} | ||
declare function clearImmediate(immediateId: NodeJS.Immediate): void; | ||
declare function queueMicrotask(callback: () => void): void; | ||
declare var require: NodeRequire; | ||
@@ -76,243 +42,105 @@ declare var module: NodeModule; | ||
// Buffer class | ||
type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "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'|'binary'(deprecated)|'hex' | ||
* Only available if `--expose-gc` is passed to the process. | ||
*/ | ||
declare class Buffer extends Uint8Array { | ||
declare 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 { | ||
/** | ||
* 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. | ||
* Returns the AbortSignal object associated with this object. | ||
*/ | ||
constructor(str: string, encoding?: BufferEncoding); | ||
readonly signal: AbortSignal; | ||
/** | ||
* 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()`). | ||
* 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. | ||
*/ | ||
constructor(size: number); | ||
abort(reason?: any): void; | ||
} | ||
/** 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 { | ||
/** | ||
* 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. | ||
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. | ||
*/ | ||
constructor(array: Uint8Array); | ||
readonly aborted: boolean; | ||
readonly reason: any; | ||
onabort: null | ((this: AbortSignal, event: Event) => any); | ||
throwIfAborted(): void; | ||
} | ||
declare var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T | ||
: { | ||
prototype: AbortController; | ||
new(): AbortController; | ||
}; | ||
declare var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T | ||
: { | ||
prototype: AbortSignal; | ||
new(): AbortSignal; | ||
abort(reason?: any): AbortSignal; | ||
timeout(milliseconds: number): AbortSignal; | ||
}; | ||
// #endregion borrowed | ||
// #region Disposable | ||
interface SymbolConstructor { | ||
/** | ||
* 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. | ||
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement. | ||
*/ | ||
constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); | ||
readonly dispose: unique symbol; | ||
/** | ||
* 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. | ||
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. | ||
*/ | ||
constructor(array: ReadonlyArray<any>); | ||
/** | ||
* 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. | ||
*/ | ||
constructor(buffer: Buffer); | ||
/** | ||
* When passed a reference to the .buffer property of a TypedArray instance, | ||
* the newly created Buffer will share the same allocated memory as the TypedArray. | ||
* The optional {byteOffset} and {length} arguments specify a memory range | ||
* within the {arrayBuffer} that will be shared by the Buffer. | ||
* | ||
* @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() | ||
*/ | ||
static 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 | ||
*/ | ||
static from(data: Uint8Array | ReadonlyArray<number>): Buffer; | ||
static from(data: WithImplicitCoercion<Uint8Array | ReadonlyArray<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'. | ||
*/ | ||
static 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 | ||
*/ | ||
static of(...items: number[]): Buffer; | ||
/** | ||
* Returns true if {obj} is a Buffer | ||
* | ||
* @param obj object to test. | ||
*/ | ||
static isBuffer(obj: any): obj is Buffer; | ||
/** | ||
* Returns true if {encoding} is a valid encoding argument. | ||
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' | ||
* | ||
* @param encoding string to test. | ||
*/ | ||
static isEncoding(encoding: string): encoding is BufferEncoding; | ||
/** | ||
* Gives the actual byte length of a string. encoding defaults to 'utf8'. | ||
* This is not the same as String.prototype.length since that returns the number of characters in a string. | ||
* | ||
* @param string string to test. | ||
* @param encoding encoding used to evaluate (defaults to 'utf8') | ||
*/ | ||
static byteLength( | ||
string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, | ||
encoding?: BufferEncoding | ||
): number; | ||
/** | ||
* Returns a buffer which is the result of concatenating all the buffers in the list together. | ||
* | ||
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. | ||
* If the list has exactly one item, then the first item of the list is returned. | ||
* If the list has more than one item, then a new Buffer is created. | ||
* | ||
* @param list An array of Buffer objects to concatenate | ||
* @param totalLength Total length of the buffers when concatenated. | ||
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. | ||
*/ | ||
static concat(list: ReadonlyArray<Uint8Array>, totalLength?: number): Buffer; | ||
/** | ||
* The same as buf1.compare(buf2). | ||
*/ | ||
static compare(buf1: Uint8Array, buf2: Uint8Array): number; | ||
/** | ||
* Allocates a new buffer of {size} octets. | ||
* | ||
* @param size count of octets to allocate. | ||
* @param fill if specified, buffer will be initialized by calling buf.fill(fill). | ||
* If parameter is omitted, buffer will be filled with zeros. | ||
* @param encoding encoding used for call to buf.fill while initalizing | ||
*/ | ||
static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; | ||
/** | ||
* Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents | ||
* of the newly created Buffer are unknown and may contain sensitive data. | ||
* | ||
* @param size count of octets to allocate | ||
*/ | ||
static allocUnsafe(size: number): Buffer; | ||
/** | ||
* Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents | ||
* of the newly created Buffer are unknown and may contain sensitive data. | ||
* | ||
* @param size count of octets to allocate | ||
*/ | ||
static allocUnsafeSlow(size: number): Buffer; | ||
/** | ||
* This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. | ||
*/ | ||
static poolSize: number; | ||
readonly asyncDispose: unique symbol; | ||
} | ||
write(string: string, encoding?: BufferEncoding): number; | ||
write(string: string, offset: number, encoding?: BufferEncoding): number; | ||
write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; | ||
toString(encoding?: BufferEncoding, start?: number, end?: number): string; | ||
toJSON(): { type: 'Buffer'; data: number[] }; | ||
equals(otherBuffer: Uint8Array): boolean; | ||
compare( | ||
otherBuffer: Uint8Array, | ||
targetStart?: number, | ||
targetEnd?: number, | ||
sourceStart?: number, | ||
sourceEnd?: number | ||
): number; | ||
copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; | ||
interface Disposable { | ||
[Symbol.dispose](): void; | ||
} | ||
interface AsyncDisposable { | ||
[Symbol.asyncDispose](): PromiseLike<void>; | ||
} | ||
// #endregion Disposable | ||
// #region ArrayLike.at() | ||
interface RelativeIndexable<T> { | ||
/** | ||
* 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 incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. | ||
* | ||
* @param begin Where the new `Buffer` will start. Default: `0`. | ||
* @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. | ||
* 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. | ||
*/ | ||
slice(begin?: 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. | ||
* | ||
* This method is compatible with `Uint8Array#subarray()`. | ||
* | ||
* @param begin Where the new `Buffer` will start. Default: `0`. | ||
* @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. | ||
*/ | ||
subarray(begin?: number, end?: number): Buffer; | ||
writeBigInt64BE(value: bigint, offset?: number): number; | ||
writeBigInt64LE(value: bigint, offset?: number): number; | ||
writeBigUInt64BE(value: bigint, offset?: number): number; | ||
writeBigUInt64LE(value: bigint, offset?: number): number; | ||
writeUIntLE(value: number, offset: number, byteLength: number): number; | ||
writeUIntBE(value: number, offset: number, byteLength: number): number; | ||
writeIntLE(value: number, offset: number, byteLength: number): number; | ||
writeIntBE(value: number, offset: number, byteLength: number): number; | ||
readBigUInt64BE(offset?: number): bigint; | ||
readBigUInt64LE(offset?: number): bigint; | ||
readBigInt64BE(offset?: number): bigint; | ||
readBigInt64LE(offset?: number): bigint; | ||
readUIntLE(offset: number, byteLength: number): number; | ||
readUIntBE(offset: number, byteLength: number): number; | ||
readIntLE(offset: number, byteLength: number): number; | ||
readIntBE(offset: number, byteLength: number): number; | ||
readUInt8(offset?: number): number; | ||
readUInt16LE(offset?: number): number; | ||
readUInt16BE(offset?: number): number; | ||
readUInt32LE(offset?: number): number; | ||
readUInt32BE(offset?: number): number; | ||
readInt8(offset?: number): number; | ||
readInt16LE(offset?: number): number; | ||
readInt16BE(offset?: number): number; | ||
readInt32LE(offset?: number): number; | ||
readInt32BE(offset?: number): number; | ||
readFloatLE(offset?: number): number; | ||
readFloatBE(offset?: number): number; | ||
readDoubleLE(offset?: number): number; | ||
readDoubleBE(offset?: number): number; | ||
reverse(): this; | ||
swap16(): Buffer; | ||
swap32(): Buffer; | ||
swap64(): Buffer; | ||
writeUInt8(value: number, offset?: number): number; | ||
writeUInt16LE(value: number, offset?: number): number; | ||
writeUInt16BE(value: number, offset?: number): number; | ||
writeUInt32LE(value: number, offset?: number): number; | ||
writeUInt32BE(value: number, offset?: number): number; | ||
writeInt8(value: number, offset?: number): number; | ||
writeInt16LE(value: number, offset?: number): number; | ||
writeInt16BE(value: number, offset?: number): number; | ||
writeInt32LE(value: number, offset?: number): number; | ||
writeInt32BE(value: number, offset?: number): number; | ||
writeFloatLE(value: number, offset?: number): number; | ||
writeFloatBE(value: number, offset?: number): number; | ||
writeDoubleLE(value: number, offset?: number): number; | ||
writeDoubleBE(value: number, offset?: number): number; | ||
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 | ||
fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; | ||
/** | ||
* @since v17.0.0 | ||
* | ||
* Creates a deep clone of an object. | ||
*/ | ||
declare function structuredClone<T>( | ||
value: T, | ||
transfer?: { transfer: ReadonlyArray<import("worker_threads").TransferListItem> }, | ||
): T; | ||
indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; | ||
lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; | ||
entries(): IterableIterator<[number, number]>; | ||
includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; | ||
keys(): IterableIterator<number>; | ||
values(): IterableIterator<number>; | ||
} | ||
/*----------------------------------------------* | ||
@@ -324,43 +152,2 @@ * * | ||
declare namespace NodeJS { | ||
interface InspectOptions { | ||
/** | ||
* If set to `true`, getters are going to be | ||
* inspected as well. If set to `'get'` only getters without setter are going | ||
* to be inspected. If set to `'set'` only getters having a corresponding | ||
* setter are going to be inspected. This might cause side effects depending on | ||
* the getter function. | ||
* @default `false` | ||
*/ | ||
getters?: 'get' | 'set' | boolean; | ||
showHidden?: boolean; | ||
/** | ||
* @default 2 | ||
*/ | ||
depth?: number | null; | ||
colors?: boolean; | ||
customInspect?: boolean; | ||
showProxy?: boolean; | ||
maxArrayLength?: number | null; | ||
/** | ||
* Specifies the maximum number of characters to | ||
* include when formatting. Set to `null` or `Infinity` to show all elements. | ||
* Set to `0` or negative to show no characters. | ||
* @default Infinity | ||
*/ | ||
maxStringLength?: number | null; | ||
breakLength?: number; | ||
/** | ||
* Setting this to `false` causes each object key | ||
* to be displayed on a new line. It will also add new lines to text that is | ||
* longer than `breakLength`. If set to a number, the most `n` inner elements | ||
* are united on a single line as long as all properties fit into | ||
* `breakLength`. Short array elements are also grouped together. Note that no | ||
* text will be reduced below 16 characters, no matter the `breakLength` size. | ||
* For more information, see the example below. | ||
* @default `true` | ||
*/ | ||
compact?: boolean | number; | ||
sorted?: boolean | ((a: string, b: string) => number); | ||
} | ||
interface CallSite { | ||
@@ -370,3 +157,3 @@ /** | ||
*/ | ||
getThis(): any; | ||
getThis(): unknown; | ||
@@ -402,3 +189,3 @@ /** | ||
*/ | ||
getFileName(): string | null; | ||
getFileName(): string | undefined; | ||
@@ -443,7 +230,6 @@ /** | ||
interface ErrnoException extends Error { | ||
errno?: number; | ||
code?: string; | ||
path?: string; | ||
syscall?: string; | ||
stack?: string; | ||
errno?: number | undefined; | ||
code?: string | undefined; | ||
path?: string | undefined; | ||
syscall?: string | undefined; | ||
} | ||
@@ -458,3 +244,3 @@ | ||
isPaused(): boolean; | ||
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T; | ||
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T; | ||
unpipe(destination?: WritableStream): this; | ||
@@ -470,72 +256,9 @@ unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; | ||
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; | ||
end(cb?: () => void): void; | ||
end(data: string | Uint8Array, cb?: () => void): void; | ||
end(str: string, encoding?: BufferEncoding, cb?: () => void): void; | ||
end(cb?: () => void): this; | ||
end(data: string | Uint8Array, cb?: () => void): this; | ||
end(str: string, encoding?: BufferEncoding, cb?: () => void): this; | ||
} | ||
interface ReadWriteStream extends ReadableStream, WritableStream { } | ||
interface ReadWriteStream extends ReadableStream, WritableStream {} | ||
interface Global { | ||
Array: typeof Array; | ||
ArrayBuffer: typeof ArrayBuffer; | ||
Boolean: typeof Boolean; | ||
Buffer: typeof Buffer; | ||
DataView: typeof DataView; | ||
Date: typeof Date; | ||
Error: typeof Error; | ||
EvalError: typeof EvalError; | ||
Float32Array: typeof Float32Array; | ||
Float64Array: typeof Float64Array; | ||
Function: typeof Function; | ||
Infinity: typeof Infinity; | ||
Int16Array: typeof Int16Array; | ||
Int32Array: typeof Int32Array; | ||
Int8Array: typeof Int8Array; | ||
Intl: typeof Intl; | ||
JSON: typeof JSON; | ||
Map: MapConstructor; | ||
Math: typeof Math; | ||
NaN: typeof NaN; | ||
Number: typeof Number; | ||
Object: typeof Object; | ||
Promise: typeof Promise; | ||
RangeError: typeof RangeError; | ||
ReferenceError: typeof ReferenceError; | ||
RegExp: typeof RegExp; | ||
Set: SetConstructor; | ||
String: typeof String; | ||
Symbol: Function; | ||
SyntaxError: typeof SyntaxError; | ||
TypeError: typeof TypeError; | ||
URIError: typeof URIError; | ||
Uint16Array: typeof Uint16Array; | ||
Uint32Array: typeof Uint32Array; | ||
Uint8Array: typeof Uint8Array; | ||
Uint8ClampedArray: typeof Uint8ClampedArray; | ||
WeakMap: WeakMapConstructor; | ||
WeakSet: WeakSetConstructor; | ||
clearImmediate: (immediateId: Immediate) => void; | ||
clearInterval: (intervalId: Timeout) => void; | ||
clearTimeout: (timeoutId: Timeout) => void; | ||
decodeURI: typeof decodeURI; | ||
decodeURIComponent: typeof decodeURIComponent; | ||
encodeURI: typeof encodeURI; | ||
encodeURIComponent: typeof encodeURIComponent; | ||
escape: (str: string) => string; | ||
eval: typeof eval; | ||
global: Global; | ||
isFinite: typeof isFinite; | ||
isNaN: typeof isNaN; | ||
parseFloat: typeof parseFloat; | ||
parseInt: typeof parseInt; | ||
setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; | ||
setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; | ||
setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; | ||
queueMicrotask: typeof queueMicrotask; | ||
undefined: typeof undefined; | ||
unescape: (str: string) => string; | ||
gc: () => void; | ||
v8debug?: any; | ||
} | ||
interface RefCounted { | ||
@@ -546,20 +269,2 @@ ref(): this; | ||
// compatibility with older typings | ||
interface Timer extends RefCounted { | ||
hasRef(): boolean; | ||
refresh(): this; | ||
[Symbol.toPrimitive](): number; | ||
} | ||
interface Immediate extends RefCounted { | ||
hasRef(): boolean; | ||
_onImmediate: Function; // to distinguish it from the Timeout class | ||
} | ||
interface Timeout extends Timer { | ||
hasRef(): boolean; | ||
refresh(): this; | ||
[Symbol.toPrimitive](): number; | ||
} | ||
type TypedArray = | ||
@@ -591,3 +296,3 @@ | Uint8Array | ||
interface RequireResolve { | ||
(id: string, options?: { paths?: string[]; }): string; | ||
(id: string, options?: { paths?: string[] | undefined }): string; | ||
paths(request: string): string[] | null; | ||
@@ -597,7 +302,11 @@ } | ||
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; | ||
".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; | ||
@@ -608,7 +317,7 @@ require: Require; | ||
loaded: boolean; | ||
/** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ | ||
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ | ||
parent: Module | null | undefined; | ||
children: Module[]; | ||
/** | ||
* @since 11.14.0 | ||
* @since v11.14.0 | ||
* | ||
@@ -628,2 +337,60 @@ * The directory name of the module. This is usually the same as the path.dirname() of the module.id. | ||
} | ||
namespace fetch { | ||
type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; | ||
type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; | ||
type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; | ||
type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; | ||
type _RequestInit = typeof globalThis extends { onmessage: any } ? {} | ||
: import("undici-types").RequestInit; | ||
type Request = globalThis.Request; | ||
type Response = globalThis.Response; | ||
type Headers = globalThis.Headers; | ||
type FormData = globalThis.FormData; | ||
type RequestInit = globalThis.RequestInit; | ||
type RequestInfo = import("undici-types").RequestInfo; | ||
type HeadersInit = import("undici-types").HeadersInit; | ||
type BodyInit = import("undici-types").BodyInit; | ||
type RequestRedirect = import("undici-types").RequestRedirect; | ||
type RequestCredentials = import("undici-types").RequestCredentials; | ||
type RequestMode = import("undici-types").RequestMode; | ||
type ReferrerPolicy = import("undici-types").ReferrerPolicy; | ||
type Dispatcher = import("undici-types").Dispatcher; | ||
type RequestDuplex = import("undici-types").RequestDuplex; | ||
} | ||
} | ||
interface RequestInit extends NodeJS.fetch._RequestInit {} | ||
declare function fetch( | ||
input: NodeJS.fetch.RequestInfo, | ||
init?: RequestInit, | ||
): Promise<Response>; | ||
interface Request extends NodeJS.fetch._Request {} | ||
declare var Request: typeof globalThis extends { | ||
onmessage: any; | ||
Request: infer T; | ||
} ? T | ||
: typeof import("undici-types").Request; | ||
interface Response extends NodeJS.fetch._Response {} | ||
declare var Response: typeof globalThis extends { | ||
onmessage: any; | ||
Response: infer T; | ||
} ? T | ||
: typeof import("undici-types").Response; | ||
interface FormData extends NodeJS.fetch._FormData {} | ||
declare var FormData: typeof globalThis extends { | ||
onmessage: any; | ||
FormData: infer T; | ||
} ? T | ||
: typeof import("undici-types").FormData; | ||
interface Headers extends NodeJS.fetch._Headers {} | ||
declare var Headers: typeof globalThis extends { | ||
onmessage: any; | ||
Headers: infer T; | ||
} ? T | ||
: typeof import("undici-types").Headers; |
@@ -1,1 +0,1 @@ | ||
declare var global: NodeJS.Global & typeof globalThis; | ||
declare var global: typeof globalThis; |
@@ -0,19 +1,31 @@ | ||
/** | ||
* 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/v20.2.0/lib/https.js) | ||
*/ | ||
declare module "https" { | ||
import * as tls from "tls"; | ||
import * as events from "events"; | ||
import * as http from "http"; | ||
import { URL } from "url"; | ||
type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; | ||
type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { | ||
rejectUnauthorized?: boolean; // Defaults to true | ||
servername?: string; // SNI TLS Extension | ||
}; | ||
import { Duplex } from "node:stream"; | ||
import * as tls from "node:tls"; | ||
import * as http from "node:http"; | ||
import { URL } from "node:url"; | ||
type ServerOptions< | ||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, | ||
Response extends typeof http.ServerResponse = typeof http.ServerResponse, | ||
> = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions<Request, Response>; | ||
type RequestOptions = | ||
& http.RequestOptions | ||
& tls.SecureContextOptions | ||
& { | ||
checkServerIdentity?: typeof tls.checkServerIdentity | undefined; | ||
rejectUnauthorized?: boolean | undefined; // Defaults to true | ||
servername?: string | undefined; // SNI TLS Extension | ||
}; | ||
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { | ||
rejectUnauthorized?: boolean; | ||
maxCachedSessions?: number; | ||
rejectUnauthorized?: boolean | undefined; | ||
maxCachedSessions?: number | undefined; | ||
} | ||
/** | ||
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. | ||
* @since v0.4.5 | ||
*/ | ||
class Agent extends http.Agent { | ||
@@ -23,16 +35,517 @@ constructor(options?: AgentOptions); | ||
} | ||
interface Server extends http.HttpBase {} | ||
class Server extends tls.Server { | ||
constructor(requestListener?: http.RequestListener); | ||
constructor(options: ServerOptions, requestListener?: http.RequestListener); | ||
interface Server< | ||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, | ||
Response extends typeof http.ServerResponse = typeof http.ServerResponse, | ||
> extends http.Server<Request, Response> {} | ||
/** | ||
* See `http.Server` for more information. | ||
* @since v0.3.4 | ||
*/ | ||
class Server< | ||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, | ||
Response extends typeof http.ServerResponse = typeof http.ServerResponse, | ||
> extends tls.Server { | ||
constructor(requestListener?: http.RequestListener<Request, Response>); | ||
constructor( | ||
options: ServerOptions<Request, Response>, | ||
requestListener?: http.RequestListener<Request, Response>, | ||
); | ||
/** | ||
* Closes all connections connected to this server. | ||
* @since v18.2.0 | ||
*/ | ||
closeAllConnections(): void; | ||
/** | ||
* Closes all connections connected to this server which are not sending a request or waiting for a response. | ||
* @since v18.2.0 | ||
*/ | ||
closeIdleConnections(): void; | ||
addListener(event: string, listener: (...args: any[]) => void): this; | ||
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; | ||
addListener( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, | ||
): this; | ||
addListener( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
addListener( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, | ||
): this; | ||
addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; | ||
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; | ||
addListener(event: "close", listener: () => void): this; | ||
addListener(event: "connection", listener: (socket: Duplex) => void): this; | ||
addListener(event: "error", listener: (err: Error) => void): this; | ||
addListener(event: "listening", listener: () => void): this; | ||
addListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; | ||
addListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; | ||
addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; | ||
addListener( | ||
event: "connect", | ||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, | ||
): this; | ||
addListener(event: "request", listener: http.RequestListener<Request, Response>): this; | ||
addListener( | ||
event: "upgrade", | ||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, | ||
): this; | ||
emit(event: string, ...args: any[]): boolean; | ||
emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; | ||
emit( | ||
event: "newSession", | ||
sessionId: Buffer, | ||
sessionData: Buffer, | ||
callback: (err: Error, resp: Buffer) => void, | ||
): boolean; | ||
emit( | ||
event: "OCSPRequest", | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
): boolean; | ||
emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; | ||
emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; | ||
emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; | ||
emit(event: "close"): boolean; | ||
emit(event: "connection", socket: Duplex): boolean; | ||
emit(event: "error", err: Error): boolean; | ||
emit(event: "listening"): boolean; | ||
emit( | ||
event: "checkContinue", | ||
req: InstanceType<Request>, | ||
res: InstanceType<Response> & { | ||
req: InstanceType<Request>; | ||
}, | ||
): boolean; | ||
emit( | ||
event: "checkExpectation", | ||
req: InstanceType<Request>, | ||
res: InstanceType<Response> & { | ||
req: InstanceType<Request>; | ||
}, | ||
): 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>; | ||
}, | ||
): boolean; | ||
emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; | ||
on( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, | ||
): this; | ||
on( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
on( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, | ||
): this; | ||
on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; | ||
on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; | ||
on(event: "close", listener: () => void): this; | ||
on(event: "connection", listener: (socket: Duplex) => void): this; | ||
on(event: "error", listener: (err: Error) => void): this; | ||
on(event: "listening", listener: () => void): this; | ||
on(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; | ||
on(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; | ||
on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; | ||
on(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; | ||
on(event: "request", listener: http.RequestListener<Request, Response>): this; | ||
on(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; | ||
once( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, | ||
): this; | ||
once( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
once( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, | ||
): this; | ||
once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; | ||
once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; | ||
once(event: "close", listener: () => void): this; | ||
once(event: "connection", listener: (socket: Duplex) => void): this; | ||
once(event: "error", listener: (err: Error) => void): this; | ||
once(event: "listening", listener: () => void): this; | ||
once(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; | ||
once(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; | ||
once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; | ||
once(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; | ||
once(event: "request", listener: http.RequestListener<Request, Response>): this; | ||
once(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; | ||
prependListener( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, | ||
): this; | ||
prependListener( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
prependListener( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, | ||
): this; | ||
prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; | ||
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; | ||
prependListener(event: "close", listener: () => void): this; | ||
prependListener(event: "connection", listener: (socket: Duplex) => void): this; | ||
prependListener(event: "error", listener: (err: Error) => void): this; | ||
prependListener(event: "listening", listener: () => void): this; | ||
prependListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; | ||
prependListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; | ||
prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; | ||
prependListener( | ||
event: "connect", | ||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, | ||
): this; | ||
prependListener(event: "request", listener: http.RequestListener<Request, Response>): this; | ||
prependListener( | ||
event: "upgrade", | ||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, | ||
): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; | ||
prependOnceListener( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, | ||
): this; | ||
prependOnceListener( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
prependOnceListener( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, | ||
): this; | ||
prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; | ||
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; | ||
prependOnceListener(event: "close", listener: () => void): this; | ||
prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; | ||
prependOnceListener(event: "error", listener: (err: Error) => void): this; | ||
prependOnceListener(event: "listening", listener: () => void): this; | ||
prependOnceListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; | ||
prependOnceListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; | ||
prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; | ||
prependOnceListener( | ||
event: "connect", | ||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, | ||
): this; | ||
prependOnceListener(event: "request", listener: http.RequestListener<Request, Response>): this; | ||
prependOnceListener( | ||
event: "upgrade", | ||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, | ||
): this; | ||
} | ||
function createServer(requestListener?: http.RequestListener): Server; | ||
function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; | ||
function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; | ||
function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; | ||
function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; | ||
function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; | ||
/** | ||
* ```js | ||
* // curl -k https://localhost:8000/ | ||
* const https = require('node:https'); | ||
* const fs = require('node:fs'); | ||
* | ||
* const options = { | ||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), | ||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), | ||
* }; | ||
* | ||
* https.createServer(options, (req, res) => { | ||
* res.writeHead(200); | ||
* res.end('hello world\n'); | ||
* }).listen(8000); | ||
* ``` | ||
* | ||
* Or | ||
* | ||
* ```js | ||
* const https = require('node:https'); | ||
* const fs = require('node:fs'); | ||
* | ||
* const options = { | ||
* pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), | ||
* passphrase: 'sample', | ||
* }; | ||
* | ||
* https.createServer(options, (req, res) => { | ||
* res.writeHead(200); | ||
* res.end('hello world\n'); | ||
* }).listen(8000); | ||
* ``` | ||
* @since v0.3.4 | ||
* @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. | ||
* @param requestListener A listener to be added to the `'request'` event. | ||
*/ | ||
function createServer< | ||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, | ||
Response extends typeof http.ServerResponse = 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, | ||
>( | ||
options: ServerOptions<Request, Response>, | ||
requestListener?: http.RequestListener<Request, Response>, | ||
): Server<Request, Response>; | ||
/** | ||
* Makes a request to a secure web server. | ||
* | ||
* The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, | ||
* `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. | ||
* | ||
* `options` can be an object, a string, or a `URL` object. If `options` is a | ||
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. | ||
* | ||
* `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to | ||
* upload a file with a POST request, then write to the `ClientRequest` object. | ||
* | ||
* ```js | ||
* const https = require('node:https'); | ||
* | ||
* const options = { | ||
* hostname: 'encrypted.google.com', | ||
* port: 443, | ||
* path: '/', | ||
* method: 'GET', | ||
* }; | ||
* | ||
* const req = https.request(options, (res) => { | ||
* console.log('statusCode:', res.statusCode); | ||
* console.log('headers:', res.headers); | ||
* | ||
* res.on('data', (d) => { | ||
* process.stdout.write(d); | ||
* }); | ||
* }); | ||
* | ||
* req.on('error', (e) => { | ||
* console.error(e); | ||
* }); | ||
* req.end(); | ||
* ``` | ||
* | ||
* Example using options from `tls.connect()`: | ||
* | ||
* ```js | ||
* const options = { | ||
* hostname: 'encrypted.google.com', | ||
* port: 443, | ||
* path: '/', | ||
* method: 'GET', | ||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), | ||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), | ||
* }; | ||
* options.agent = new https.Agent(options); | ||
* | ||
* const req = https.request(options, (res) => { | ||
* // ... | ||
* }); | ||
* ``` | ||
* | ||
* Alternatively, opt out of connection pooling by not using an `Agent`. | ||
* | ||
* ```js | ||
* const options = { | ||
* hostname: 'encrypted.google.com', | ||
* port: 443, | ||
* path: '/', | ||
* method: 'GET', | ||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), | ||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), | ||
* agent: false, | ||
* }; | ||
* | ||
* const req = https.request(options, (res) => { | ||
* // ... | ||
* }); | ||
* ``` | ||
* | ||
* Example using a `URL` as `options`: | ||
* | ||
* ```js | ||
* const options = new URL('https://abc:xyz@example.com'); | ||
* | ||
* const req = https.request(options, (res) => { | ||
* // ... | ||
* }); | ||
* ``` | ||
* | ||
* 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'); | ||
* | ||
* function sha256(s) { | ||
* return crypto.createHash('sha256').update(s).digest('base64'); | ||
* } | ||
* const options = { | ||
* hostname: 'github.com', | ||
* port: 443, | ||
* path: '/', | ||
* method: 'GET', | ||
* checkServerIdentity: function(host, cert) { | ||
* // Make sure the certificate is issued to the host we are connected to | ||
* const err = tls.checkServerIdentity(host, cert); | ||
* if (err) { | ||
* return err; | ||
* } | ||
* | ||
* // Pin the public key, similar to HPKP pin-sha256 pinning | ||
* const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; | ||
* if (sha256(cert.pubkey) !== pubkey256) { | ||
* const msg = 'Certificate verification error: ' + | ||
* `The public key of '${cert.subject.CN}' ` + | ||
* 'does not match our pinned fingerprint'; | ||
* return new Error(msg); | ||
* } | ||
* | ||
* // Pin the exact certificate, rather than the pub key | ||
* const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + | ||
* 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; | ||
* if (cert.fingerprint256 !== cert256) { | ||
* const msg = 'Certificate verification error: ' + | ||
* `The certificate of '${cert.subject.CN}' ` + | ||
* 'does not match our pinned fingerprint'; | ||
* return new Error(msg); | ||
* } | ||
* | ||
* // This loop is informational only. | ||
* // Print the certificate and public key fingerprints of all certs in the | ||
* // chain. Its common to pin the public key of the issuer on the public | ||
* // internet, while pinning the public key of the service in sensitive | ||
* // environments. | ||
* do { | ||
* console.log('Subject Common Name:', cert.subject.CN); | ||
* console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); | ||
* | ||
* hash = crypto.createHash('sha256'); | ||
* console.log(' Public key ping-sha256:', sha256(cert.pubkey)); | ||
* | ||
* lastprint256 = cert.fingerprint256; | ||
* cert = cert.issuerCertificate; | ||
* } while (cert.fingerprint256 !== lastprint256); | ||
* | ||
* }, | ||
* }; | ||
* | ||
* options.agent = new https.Agent(options); | ||
* const req = https.request(options, (res) => { | ||
* console.log('All OK. Server matched our pinned cert or public key'); | ||
* console.log('statusCode:', res.statusCode); | ||
* // Print the HPKP values | ||
* console.log('headers:', res.headers['public-key-pins']); | ||
* | ||
* res.on('data', (d) => {}); | ||
* }); | ||
* | ||
* req.on('error', (e) => { | ||
* console.error(e.message); | ||
* }); | ||
* req.end(); | ||
* ``` | ||
* | ||
* Outputs for example: | ||
* | ||
* ```text | ||
* Subject Common Name: github.com | ||
* Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 | ||
* Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= | ||
* Subject Common Name: DigiCert SHA2 Extended Validation Server CA | ||
* Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A | ||
* Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= | ||
* Subject Common Name: DigiCert High Assurance EV Root CA | ||
* Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF | ||
* Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= | ||
* All OK. Server matched our pinned cert or public key | ||
* statusCode: 200 | ||
* headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; | ||
* pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; | ||
* pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains | ||
* ``` | ||
* @since v0.3.6 | ||
* @param options Accepts all `options` from `request`, with some differences in default values: | ||
*/ | ||
function request( | ||
options: RequestOptions | string | URL, | ||
callback?: (res: http.IncomingMessage) => void, | ||
): http.ClientRequest; | ||
function request( | ||
url: string | URL, | ||
options: RequestOptions, | ||
callback?: (res: http.IncomingMessage) => void, | ||
): http.ClientRequest; | ||
/** | ||
* Like `http.get()` but for HTTPS. | ||
* | ||
* `options` can be an object, a string, or a `URL` object. If `options` is a | ||
* 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'); | ||
* | ||
* https.get('https://encrypted.google.com/', (res) => { | ||
* console.log('statusCode:', res.statusCode); | ||
* console.log('headers:', res.headers); | ||
* | ||
* res.on('data', (d) => { | ||
* process.stdout.write(d); | ||
* }); | ||
* | ||
* }).on('error', (e) => { | ||
* console.error(e); | ||
* }); | ||
* ``` | ||
* @since v0.3.6 | ||
* @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. | ||
*/ | ||
function get( | ||
options: RequestOptions | string | URL, | ||
callback?: (res: http.IncomingMessage) => void, | ||
): http.ClientRequest; | ||
function get( | ||
url: string | URL, | ||
options: RequestOptions, | ||
callback?: (res: http.IncomingMessage) => void, | ||
): http.ClientRequest; | ||
let globalAgent: Agent; | ||
} | ||
declare module "node:https" { | ||
export * from "https"; | ||
} |
@@ -1,62 +0,88 @@ | ||
// Type definitions for non-npm package Node.js 14.14 | ||
// Project: http://nodejs.org/ | ||
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft> | ||
// DefinitelyTyped <https://github.com/DefinitelyTyped> | ||
// Alberto Schiabel <https://github.com/jkomyno> | ||
// Alexander T. <https://github.com/a-tarasyuk> | ||
// Alvis HT Tang <https://github.com/alvis> | ||
// Andrew Makarov <https://github.com/r3nya> | ||
// Benjamin Toueg <https://github.com/btoueg> | ||
// Bruno Scheufler <https://github.com/brunoscheufler> | ||
// 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> | ||
// Flarna <https://github.com/Flarna> | ||
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK> | ||
// Hoàng Văn Khải <https://github.com/KSXGitHub> | ||
// 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> | ||
// Nicolas Even <https://github.com/n-e> | ||
// Nikita Galkin <https://github.com/galkin> | ||
// Parambir Singh <https://github.com/parambirs> | ||
// Sebastian Silbermann <https://github.com/eps1lon> | ||
// Simon Schick <https://github.com/SimonSchick> | ||
// 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> | ||
// Jordi Oliveras Rovira <https://github.com/j-oliveras> | ||
// Thanik Bhongbhibhat <https://github.com/bhongy> | ||
// Marcin Kopacz <https://github.com/chyzwar> | ||
// Trivikram Kamat <https://github.com/trivikr> | ||
// Minh Son Nguyen <https://github.com/nguymin4> | ||
// Junxiao Shi <https://github.com/yoursunny> | ||
// Ilia Baryshnikov <https://github.com/qwelias> | ||
// ExE Boss <https://github.com/ExE-Boss> | ||
// Surasak Chaisurin <https://github.com/Ryan-Willpower> | ||
// Piotr Błażejewicz <https://github.com/peterblazejewicz> | ||
// Anna Henningsen <https://github.com/addaleax> | ||
// Jason Kwok <https://github.com/JasonHK> | ||
// Victor Perin <https://github.com/victorperin> | ||
// Yongsheng Zhang <https://github.com/ZYSzys> | ||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped | ||
/** | ||
* License for programmatically and manually incorporated | ||
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc | ||
* | ||
* Copyright Node.js contributors. All rights reserved. | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to | ||
* deal in the Software without restriction, including without limitation the | ||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | ||
* sell copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | ||
* IN THE SOFTWARE. | ||
*/ | ||
// NOTE: These definitions support NodeJS and TypeScript 3.7. | ||
// Typically type modifications should be made in base.d.ts instead of here | ||
// NOTE: These definitions support NodeJS and TypeScript 4.9+. | ||
/// <reference path="base.d.ts" /> | ||
// Reference required types from the default lib: | ||
/// <reference lib="es2020" /> | ||
/// <reference lib="esnext.asynciterable" /> | ||
/// <reference lib="esnext.intl" /> | ||
/// <reference lib="esnext.bigint" /> | ||
// NOTE: TypeScript version-specific augmentations can be found in the following paths: | ||
// - ~/base.d.ts - Shared definitions common to all TypeScript versions | ||
// - ~/index.d.ts - Definitions specific to TypeScript 2.8 | ||
// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 | ||
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: | ||
/// <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" /> | ||
/// <reference path="cluster.d.ts" /> | ||
/// <reference path="console.d.ts" /> | ||
/// <reference path="constants.d.ts" /> | ||
/// <reference path="crypto.d.ts" /> | ||
/// <reference path="dgram.d.ts" /> | ||
/// <reference path="diagnostics_channel.d.ts" /> | ||
/// <reference path="dns.d.ts" /> | ||
/// <reference path="dns/promises.d.ts" /> | ||
/// <reference path="dns/promises.d.ts" /> | ||
/// <reference path="domain.d.ts" /> | ||
/// <reference path="dom-events.d.ts" /> | ||
/// <reference path="events.d.ts" /> | ||
/// <reference path="fs.d.ts" /> | ||
/// <reference path="fs/promises.d.ts" /> | ||
/// <reference path="http.d.ts" /> | ||
/// <reference path="http2.d.ts" /> | ||
/// <reference path="https.d.ts" /> | ||
/// <reference path="inspector.d.ts" /> | ||
/// <reference path="module.d.ts" /> | ||
/// <reference path="net.d.ts" /> | ||
/// <reference path="os.d.ts" /> | ||
/// <reference path="path.d.ts" /> | ||
/// <reference path="perf_hooks.d.ts" /> | ||
/// <reference path="process.d.ts" /> | ||
/// <reference path="punycode.d.ts" /> | ||
/// <reference path="querystring.d.ts" /> | ||
/// <reference path="readline.d.ts" /> | ||
/// <reference path="readline/promises.d.ts" /> | ||
/// <reference path="repl.d.ts" /> | ||
/// <reference path="stream.d.ts" /> | ||
/// <reference path="stream/promises.d.ts" /> | ||
/// <reference path="stream/consumers.d.ts" /> | ||
/// <reference path="stream/web.d.ts" /> | ||
/// <reference path="string_decoder.d.ts" /> | ||
/// <reference path="test.d.ts" /> | ||
/// <reference path="timers.d.ts" /> | ||
/// <reference path="timers/promises.d.ts" /> | ||
/// <reference path="tls.d.ts" /> | ||
/// <reference path="trace_events.d.ts" /> | ||
/// <reference path="tty.d.ts" /> | ||
/// <reference path="url.d.ts" /> | ||
/// <reference path="util.d.ts" /> | ||
/// <reference path="v8.d.ts" /> | ||
/// <reference path="vm.d.ts" /> | ||
/// <reference path="wasi.d.ts" /> | ||
/// <reference path="worker_threads.d.ts" /> | ||
/// <reference path="zlib.d.ts" /> | ||
// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides | ||
// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions | ||
// prior to TypeScript 3.5, so the older definitions will be found here. | ||
/// <reference path="globals.global.d.ts" /> |
@@ -0,10 +1,51 @@ | ||
/** | ||
* @since v0.3.7 | ||
* @experimental | ||
*/ | ||
declare module "module" { | ||
import { URL } from "url"; | ||
import { URL } from "node:url"; | ||
import { MessagePort } from "node:worker_threads"; | ||
namespace Module { | ||
/** | ||
* 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. | ||
* 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'); | ||
* | ||
* fs.readFile = newAPI; | ||
* | ||
* delete fs.readFileSync; | ||
* | ||
* function newAPI() { | ||
* // ... | ||
* } | ||
* | ||
* fs.newAPI = newAPI; | ||
* | ||
* syncBuiltinESMExports(); | ||
* | ||
* import('node:fs').then((esmFS) => { | ||
* // It syncs the existing readFile property with the new value | ||
* assert.strictEqual(esmFS.readFile, newAPI); | ||
* // readFileSync has been deleted from the required fs | ||
* assert.strictEqual('readFileSync' in fs, false); | ||
* // syncBuiltinESMExports() does not remove readFileSync from esmFS | ||
* assert.strictEqual('readFileSync' in esmFS, true); | ||
* // syncBuiltinESMExports() does not add names | ||
* assert.strictEqual(esmFS.newAPI, undefined); | ||
* }); | ||
* ``` | ||
* @since v12.12.0 | ||
*/ | ||
function syncBuiltinESMExports(): void; | ||
/** | ||
* `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; | ||
@@ -20,3 +61,2 @@ interface SourceMapPayload { | ||
} | ||
interface SourceMapping { | ||
@@ -29,9 +69,181 @@ generatedLine: number; | ||
} | ||
interface SourceOrigin { | ||
/** | ||
* The name of the range in the source map, if one was provided | ||
*/ | ||
name?: string; | ||
/** | ||
* The file name of the original source, as reported in the SourceMap | ||
*/ | ||
fileName: string; | ||
/** | ||
* The 1-indexed lineNumber of the corresponding call site in the original source | ||
*/ | ||
lineNumber: number; | ||
/** | ||
* The 1-indexed columnNumber of the corresponding call site in the original source | ||
*/ | ||
columnNumber: number; | ||
} | ||
/** | ||
* @since v13.7.0, v12.17.0 | ||
*/ | ||
class SourceMap { | ||
/** | ||
* Getter for the payload used to construct the `SourceMap` instance. | ||
*/ | ||
readonly payload: SourceMapPayload; | ||
constructor(payload: SourceMapPayload); | ||
findEntry(line: number, column: number): SourceMapping; | ||
/** | ||
* Given a line offset and column offset in the generated source | ||
* file, returns an object representing the SourceMap range in the | ||
* original file if found, or an empty object if not. | ||
* | ||
* The object returned contains the following keys: | ||
* | ||
* The returned value represents the raw range as it appears in the | ||
* SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and | ||
* column numbers as they appear in Error messages and CallSite | ||
* objects. | ||
* | ||
* To get the corresponding 1-indexed line and column numbers from a | ||
* lineNumber and columnNumber as they are reported by Error stacks | ||
* and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` | ||
* @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; | ||
/** | ||
* 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. | ||
* | ||
* If the `lineNumber` and `columnNumber` provided are not found in any source map, | ||
* then an empty object is returned. | ||
* @param lineNumber The 1-indexed line number of the call site in the generated source | ||
* @param columnNumber The 1-indexed column number of the call site in the generated source | ||
*/ | ||
findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; | ||
} | ||
interface ImportAssertions 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 | ||
*/ | ||
importAssertions: ImportAssertions; | ||
/** | ||
* 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 assertions to use when caching the module (optional; if excluded the input will be used) | ||
*/ | ||
importAssertions?: ImportAssertions | 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 | ||
*/ | ||
importAssertions: ImportAssertions; | ||
} | ||
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 {} | ||
@@ -41,15 +253,38 @@ class Module { | ||
static wrap(code: string): string; | ||
/** | ||
* @deprecated Deprecated since: v12.2.0. Please use createRequire() instead. | ||
*/ | ||
static createRequireFromPath(path: string): NodeRequire; | ||
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); | ||
} | ||
global { | ||
interface ImportMeta { | ||
url: string; | ||
/** | ||
* Provides 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. | ||
* | ||
* @since v20.6.0 | ||
* | ||
* @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. | ||
*/ | ||
resolve(specifier: string, parent?: string | URL | undefined): string; | ||
} | ||
} | ||
export = Module; | ||
} | ||
declare module "node:module" { | ||
import module = require("module"); | ||
export = module; | ||
} |
@@ -0,8 +1,24 @@ | ||
/** | ||
* > Stability: 2 - Stable | ||
* | ||
* The `node:net` module provides an asynchronous network API for creating stream-based | ||
* TCP or `IPC` servers ({@link createServer}) and clients | ||
* ({@link createConnection}). | ||
* | ||
* It can be accessed using: | ||
* | ||
* ```js | ||
* const net = require('node:net'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) | ||
*/ | ||
declare module "net" { | ||
import * as stream from "stream"; | ||
import * as events from "events"; | ||
import * as dns from "dns"; | ||
type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; | ||
import * as stream from "node:stream"; | ||
import { Abortable, EventEmitter } from "node:events"; | ||
import * as dns from "node:dns"; | ||
type LookupFunction = ( | ||
hostname: string, | ||
options: dns.LookupAllOptions, | ||
callback: (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => void, | ||
) => void; | ||
interface AddressInfo { | ||
@@ -13,10 +29,9 @@ address: string; | ||
} | ||
interface SocketConstructorOpts { | ||
fd?: number; | ||
allowHalfOpen?: boolean; | ||
readable?: boolean; | ||
writable?: boolean; | ||
fd?: number | undefined; | ||
allowHalfOpen?: boolean | undefined; | ||
readable?: boolean | undefined; | ||
writable?: boolean | undefined; | ||
signal?: AbortSignal; | ||
} | ||
interface OnReadOpts { | ||
@@ -31,3 +46,2 @@ buffer: Uint8Array | (() => Uint8Array); | ||
} | ||
interface ConnectOpts { | ||
@@ -39,28 +53,87 @@ /** | ||
*/ | ||
onread?: OnReadOpts; | ||
onread?: OnReadOpts | undefined; | ||
} | ||
interface TcpSocketConnectOpts extends ConnectOpts { | ||
port: number; | ||
host?: string; | ||
localAddress?: string; | ||
localPort?: number; | ||
hints?: number; | ||
family?: number; | ||
lookup?: LookupFunction; | ||
host?: string | undefined; | ||
localAddress?: string | undefined; | ||
localPort?: number | undefined; | ||
hints?: number | undefined; | ||
family?: number | undefined; | ||
lookup?: LookupFunction | undefined; | ||
noDelay?: boolean | undefined; | ||
keepAlive?: boolean | undefined; | ||
keepAliveInitialDelay?: number | undefined; | ||
/** | ||
* @since v18.13.0 | ||
*/ | ||
autoSelectFamily?: boolean | undefined; | ||
/** | ||
* @since v18.13.0 | ||
*/ | ||
autoSelectFamilyAttemptTimeout?: number | undefined; | ||
} | ||
interface IpcSocketConnectOpts extends ConnectOpts { | ||
path: string; | ||
} | ||
type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; | ||
type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; | ||
/** | ||
* This class is an abstraction of a TCP socket or a streaming `IPC` endpoint | ||
* (uses named pipes on Windows, and Unix domain sockets otherwise). It is also | ||
* an `EventEmitter`. | ||
* | ||
* A `net.Socket` can be created by the user and used directly to interact with | ||
* a server. For example, it is returned by {@link createConnection}, | ||
* so the user can use it to talk to the server. | ||
* | ||
* It can also be created by Node.js and passed to the user when a connection | ||
* is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use | ||
* it to interact with the client. | ||
* @since v0.3.4 | ||
*/ | ||
class Socket extends stream.Duplex { | ||
constructor(options?: SocketConstructorOpts); | ||
// Extended base methods | ||
/** | ||
* Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. | ||
* If the socket is still writable it implicitly calls `socket.end()`. | ||
* @since v0.3.4 | ||
*/ | ||
destroySoon(): void; | ||
/** | ||
* Sends data on the socket. The second parameter specifies the encoding in the | ||
* case of a string. It defaults to UTF8 encoding. | ||
* | ||
* Returns `true` if the entire data was flushed successfully to the kernel | ||
* buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. | ||
* | ||
* The optional `callback` parameter will be executed when the data is finally | ||
* written out, which may not be immediately. | ||
* | ||
* See `Writable` stream `write()` method for more | ||
* information. | ||
* @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; | ||
/** | ||
* Initiate a connection on a given socket. | ||
* | ||
* Possible signatures: | ||
* | ||
* * `socket.connect(options[, connectListener])` | ||
* * `socket.connect(path[, connectListener])` for `IPC` connections. | ||
* * `socket.connect(port[, host][, connectListener])` for TCP connections. | ||
* * Returns: `net.Socket` The socket itself. | ||
* | ||
* This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, | ||
* instead of a `'connect'` event, an `'error'` event will be emitted with | ||
* the error passed to the `'error'` listener. | ||
* The last parameter `connectListener`, if supplied, will be added as a listener | ||
* for the `'connect'` event **once**. | ||
* | ||
* This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined | ||
* behavior. | ||
*/ | ||
connect(options: SocketConnectOpts, connectionListener?: () => void): this; | ||
@@ -70,31 +143,225 @@ connect(port: number, host: string, connectionListener?: () => void): this; | ||
connect(path: string, connectionListener?: () => void): this; | ||
/** | ||
* Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. | ||
* @since v0.1.90 | ||
* @return The socket itself. | ||
*/ | ||
setEncoding(encoding?: BufferEncoding): this; | ||
/** | ||
* Pauses the reading of data. That is, `'data'` events will not be emitted. | ||
* Useful to throttle back an upload. | ||
* @return The socket itself. | ||
*/ | ||
pause(): this; | ||
/** | ||
* Close the TCP connection by sending an RST packet and destroy the stream. | ||
* If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. | ||
* Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. | ||
* If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. | ||
* @since v18.3.0, v16.17.0 | ||
*/ | ||
resetAndDestroy(): this; | ||
/** | ||
* Resumes reading after a call to `socket.pause()`. | ||
* @return The socket itself. | ||
*/ | ||
resume(): this; | ||
/** | ||
* Sets the socket to timeout after `timeout` milliseconds of inactivity on | ||
* the socket. By default `net.Socket` do not have a timeout. | ||
* | ||
* When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to | ||
* end the connection. | ||
* | ||
* ```js | ||
* socket.setTimeout(3000); | ||
* socket.on('timeout', () => { | ||
* console.log('socket timeout'); | ||
* socket.end(); | ||
* }); | ||
* ``` | ||
* | ||
* If `timeout` is 0, then the existing idle timeout is disabled. | ||
* | ||
* The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. | ||
* @since v0.1.90 | ||
* @return The socket itself. | ||
*/ | ||
setTimeout(timeout: number, callback?: () => void): this; | ||
/** | ||
* Enable/disable the use of Nagle's algorithm. | ||
* | ||
* When a TCP connection is created, it will have Nagle's algorithm enabled. | ||
* | ||
* Nagle's algorithm delays data before it is sent via the network. It attempts | ||
* to optimize throughput at the expense of latency. | ||
* | ||
* Passing `true` for `noDelay` or not passing an argument will disable Nagle's | ||
* algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's | ||
* algorithm. | ||
* @since v0.1.90 | ||
* @param [noDelay=true] | ||
* @return The socket itself. | ||
*/ | ||
setNoDelay(noDelay?: boolean): this; | ||
/** | ||
* Enable/disable keep-alive functionality, and optionally set the initial | ||
* delay before the first keepalive probe is sent on an idle socket. | ||
* | ||
* Set `initialDelay` (in milliseconds) to set the delay between the last | ||
* data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default | ||
* (or previous) setting. | ||
* | ||
* Enabling the keep-alive functionality will set the following socket options: | ||
* | ||
* * `SO_KEEPALIVE=1` | ||
* * `TCP_KEEPIDLE=initialDelay` | ||
* * `TCP_KEEPCNT=10` | ||
* * `TCP_KEEPINTVL=1` | ||
* @since v0.1.92 | ||
* @param [enable=false] | ||
* @param [initialDelay=0] | ||
* @return The socket itself. | ||
*/ | ||
setKeepAlive(enable?: boolean, initialDelay?: number): this; | ||
/** | ||
* Returns the bound `address`, the address `family` name and `port` of the | ||
* socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` | ||
* @since v0.1.90 | ||
*/ | ||
address(): AddressInfo | {}; | ||
/** | ||
* Calling `unref()` on a socket will allow the program to exit if this is the only | ||
* active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. | ||
* @since v0.9.1 | ||
* @return The socket itself. | ||
*/ | ||
unref(): this; | ||
/** | ||
* Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). | ||
* If the socket is `ref`ed calling `ref` again will have no effect. | ||
* @since v0.9.1 | ||
* @return The socket itself. | ||
*/ | ||
ref(): this; | ||
/** @deprecated since v14.6.0 - Use `writableLength` instead. */ | ||
/** | ||
* This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` | ||
* and it is an array of the addresses that have been attempted. | ||
* | ||
* Each address is a string in the form of `$IP:$PORT`. | ||
* If the connection was successful, then the last address is the one that the socket is currently connected to. | ||
* @since v19.4.0 | ||
*/ | ||
readonly autoSelectFamilyAttemptedAddresses: string[]; | ||
/** | ||
* This property shows the number of characters buffered for writing. The buffer | ||
* may contain strings whose length after encoding is not yet known. So this number | ||
* is only an approximation of the number of bytes in the buffer. | ||
* | ||
* `net.Socket` has the property that `socket.write()` always works. This is to | ||
* help users get up and running quickly. The computer cannot always keep up | ||
* with the amount of data that is written to a socket. The network connection | ||
* simply might be too slow. Node.js will internally queue up the data written to a | ||
* socket and send it out over the wire when it is possible. | ||
* | ||
* The consequence of this internal buffering is that memory may grow. | ||
* Users who experience large or growing `bufferSize` should attempt to | ||
* "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. | ||
* @since v0.3.8 | ||
* @deprecated Since v14.6.0 - Use `writableLength` instead. | ||
*/ | ||
readonly bufferSize: number; | ||
/** | ||
* The amount of received bytes. | ||
* @since v0.5.3 | ||
*/ | ||
readonly bytesRead: number; | ||
/** | ||
* The amount of bytes sent. | ||
* @since v0.5.3 | ||
*/ | ||
readonly bytesWritten: number; | ||
/** | ||
* If `true`,`socket.connect(options[, connectListener])` was | ||
* called and has not yet finished. It will stay `true` until the socket becomes | ||
* connected, then it is set to `false` and the `'connect'` event is emitted. Note | ||
* that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. | ||
* @since v6.1.0 | ||
*/ | ||
readonly connecting: boolean; | ||
/** | ||
* This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting | ||
* (see `socket.connecting`). | ||
* @since v11.2.0, v10.16.0 | ||
*/ | ||
readonly pending: boolean; | ||
/** | ||
* See `writable.destroyed` for further details. | ||
*/ | ||
readonly destroyed: boolean; | ||
readonly localAddress: string; | ||
readonly localPort: number; | ||
readonly remoteAddress?: string; | ||
readonly remoteFamily?: string; | ||
readonly remotePort?: number; | ||
// Extended base methods | ||
end(cb?: () => void): void; | ||
end(buffer: Uint8Array | string, cb?: () => void): void; | ||
end(str: Uint8Array | string, encoding?: BufferEncoding, cb?: () => void): void; | ||
/** | ||
* The string representation of the local IP address the remote client is | ||
* connecting on. For example, in a server listening on `'0.0.0.0'`, if a client | ||
* connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. | ||
* @since v0.9.6 | ||
*/ | ||
readonly localAddress?: string; | ||
/** | ||
* The numeric representation of the local port. For example, `80` or `21`. | ||
* @since v0.9.6 | ||
*/ | ||
readonly localPort?: number; | ||
/** | ||
* The string representation of the local IP family. `'IPv4'` or `'IPv6'`. | ||
* @since v18.8.0, v16.18.0 | ||
*/ | ||
readonly localFamily?: string; | ||
/** | ||
* This property represents the state of the connection as a string. | ||
* | ||
* * If the stream is connecting `socket.readyState` is `opening`. | ||
* * If the stream is readable and writable, it is `open`. | ||
* * If the stream is readable and not writable, it is `readOnly`. | ||
* * If the stream is not readable and writable, it is `writeOnly`. | ||
* @since v0.5.0 | ||
*/ | ||
readonly readyState: SocketReadyState; | ||
/** | ||
* The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if | ||
* the socket is destroyed (for example, if the client disconnected). | ||
* @since v0.5.10 | ||
*/ | ||
readonly remoteAddress?: string | undefined; | ||
/** | ||
* The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if | ||
* the socket is destroyed (for example, if the client disconnected). | ||
* @since v0.11.14 | ||
*/ | ||
readonly remoteFamily?: string | undefined; | ||
/** | ||
* The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if | ||
* the socket is destroyed (for example, if the client disconnected). | ||
* @since v0.5.10 | ||
*/ | ||
readonly remotePort?: number | undefined; | ||
/** | ||
* The socket timeout in milliseconds as set by `socket.setTimeout()`. | ||
* It is `undefined` if a timeout has not been set. | ||
* @since v10.7.0 | ||
*/ | ||
readonly timeout?: number | undefined; | ||
/** | ||
* Half-closes the socket. i.e., it sends a FIN packet. It is possible the | ||
* server will still send some data. | ||
* | ||
* See `writable.end()` for further details. | ||
* @since v0.1.90 | ||
* @param [encoding='utf8'] Only used when data is `string`. | ||
* @param callback Optional callback for when the socket is finished. | ||
* @return The socket itself. | ||
*/ | ||
end(callback?: () => void): this; | ||
end(buffer: Uint8Array | string, callback?: () => void): this; | ||
end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; | ||
/** | ||
* events.EventEmitter | ||
@@ -108,6 +375,7 @@ * 1. close | ||
* 7. lookup | ||
* 8. timeout | ||
* 8. ready | ||
* 9. timeout | ||
*/ | ||
addListener(event: string, listener: (...args: any[]) => void): this; | ||
addListener(event: "close", listener: (had_error: boolean) => void): this; | ||
addListener(event: "close", listener: (hadError: boolean) => void): this; | ||
addListener(event: "connect", listener: () => void): this; | ||
@@ -118,7 +386,10 @@ addListener(event: "data", listener: (data: Buffer) => void): this; | ||
addListener(event: "error", listener: (err: Error) => void): this; | ||
addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; | ||
addListener( | ||
event: "lookup", | ||
listener: (err: Error, address: string, family: string | number, host: string) => void, | ||
): this; | ||
addListener(event: "ready", listener: () => void): this; | ||
addListener(event: "timeout", listener: () => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
emit(event: "close", had_error: boolean): boolean; | ||
emit(event: "close", hadError: boolean): boolean; | ||
emit(event: "connect"): boolean; | ||
@@ -130,6 +401,6 @@ emit(event: "data", data: Buffer): boolean; | ||
emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; | ||
emit(event: "ready"): boolean; | ||
emit(event: "timeout"): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
on(event: "close", listener: (had_error: boolean) => void): this; | ||
on(event: "close", listener: (hadError: boolean) => void): this; | ||
on(event: "connect", listener: () => void): this; | ||
@@ -140,7 +411,10 @@ on(event: "data", listener: (data: Buffer) => void): this; | ||
on(event: "error", listener: (err: Error) => void): this; | ||
on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; | ||
on( | ||
event: "lookup", | ||
listener: (err: Error, address: string, family: string | number, host: string) => void, | ||
): this; | ||
on(event: "ready", listener: () => void): this; | ||
on(event: "timeout", listener: () => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
once(event: "close", listener: (had_error: boolean) => void): this; | ||
once(event: "close", listener: (hadError: boolean) => void): this; | ||
once(event: "connect", listener: () => void): this; | ||
@@ -151,7 +425,10 @@ once(event: "data", listener: (data: Buffer) => void): this; | ||
once(event: "error", listener: (err: Error) => void): this; | ||
once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; | ||
once( | ||
event: "lookup", | ||
listener: (err: Error, address: string, family: string | number, host: string) => void, | ||
): this; | ||
once(event: "ready", listener: () => void): this; | ||
once(event: "timeout", listener: () => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
prependListener(event: "close", listener: (had_error: boolean) => void): this; | ||
prependListener(event: "close", listener: (hadError: boolean) => void): this; | ||
prependListener(event: "connect", listener: () => void): this; | ||
@@ -162,7 +439,10 @@ prependListener(event: "data", listener: (data: Buffer) => void): this; | ||
prependListener(event: "error", listener: (err: Error) => void): this; | ||
prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; | ||
prependListener( | ||
event: "lookup", | ||
listener: (err: Error, address: string, family: string | number, host: string) => void, | ||
): this; | ||
prependListener(event: "ready", listener: () => void): this; | ||
prependListener(event: "timeout", listener: () => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; | ||
prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; | ||
prependOnceListener(event: "connect", listener: () => void): this; | ||
@@ -173,25 +453,109 @@ prependOnceListener(event: "data", listener: (data: Buffer) => void): this; | ||
prependOnceListener(event: "error", listener: (err: Error) => void): this; | ||
prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; | ||
prependOnceListener( | ||
event: "lookup", | ||
listener: (err: Error, address: string, family: string | number, host: string) => void, | ||
): this; | ||
prependOnceListener(event: "ready", listener: () => void): this; | ||
prependOnceListener(event: "timeout", listener: () => void): this; | ||
} | ||
interface ListenOptions { | ||
port?: number; | ||
host?: string; | ||
backlog?: number; | ||
path?: string; | ||
exclusive?: boolean; | ||
readableAll?: boolean; | ||
writableAll?: boolean; | ||
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; | ||
/** | ||
* @default false | ||
*/ | ||
ipv6Only?: boolean; | ||
ipv6Only?: boolean | undefined; | ||
} | ||
// https://github.com/nodejs/node/blob/master/lib/net.js | ||
class Server extends events.EventEmitter { | ||
interface ServerOpts { | ||
/** | ||
* Indicates whether half-opened TCP connections are allowed. | ||
* @default false | ||
*/ | ||
allowHalfOpen?: boolean | undefined; | ||
/** | ||
* Indicates whether the socket should be paused on incoming connections. | ||
* @default false | ||
*/ | ||
pauseOnConnect?: boolean | undefined; | ||
/** | ||
* If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. | ||
* @default false | ||
* @since v16.5.0 | ||
*/ | ||
noDelay?: 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])`. | ||
* @default false | ||
* @since v16.5.0 | ||
*/ | ||
keepAlive?: boolean | undefined; | ||
/** | ||
* If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. | ||
* @default 0 | ||
* @since v16.5.0 | ||
*/ | ||
keepAliveInitialDelay?: number | undefined; | ||
} | ||
interface DropArgument { | ||
localAddress?: string; | ||
localPort?: number; | ||
localFamily?: string; | ||
remoteAddress?: string; | ||
remotePort?: number; | ||
remoteFamily?: string; | ||
} | ||
/** | ||
* This class is used to create a TCP or `IPC` server. | ||
* @since v0.1.90 | ||
*/ | ||
class Server extends EventEmitter { | ||
constructor(connectionListener?: (socket: Socket) => void); | ||
constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); | ||
constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); | ||
/** | ||
* Start a server listening for connections. A `net.Server` can be a TCP or | ||
* an `IPC` server depending on what it listens to. | ||
* | ||
* Possible signatures: | ||
* | ||
* * `server.listen(handle[, backlog][, callback])` | ||
* * `server.listen(options[, callback])` | ||
* * `server.listen(path[, backlog][, callback])` for `IPC` servers | ||
* * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers | ||
* | ||
* This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` | ||
* event. | ||
* | ||
* All `listen()` methods can take a `backlog` parameter to specify the maximum | ||
* length of the queue of pending connections. The actual length will be determined | ||
* by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). | ||
* | ||
* All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for | ||
* details). | ||
* | ||
* The `server.listen()` method can be called again if and only if there was an | ||
* error during the first `server.listen()` call or `server.close()` has been | ||
* called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. | ||
* | ||
* One of the most common errors raised when listening is `EADDRINUSE`. | ||
* This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry | ||
* after a certain amount of time: | ||
* | ||
* ```js | ||
* server.on('error', (e) => { | ||
* if (e.code === 'EADDRINUSE') { | ||
* console.error('Address in use, retrying...'); | ||
* setTimeout(() => { | ||
* server.close(); | ||
* server.listen(PORT, HOST); | ||
* }, 1000); | ||
* } | ||
* }); | ||
* ``` | ||
*/ | ||
listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; | ||
@@ -206,11 +570,75 @@ listen(port?: number, hostname?: string, listeningListener?: () => void): this; | ||
listen(handle: any, listeningListener?: () => void): this; | ||
/** | ||
* Stops the server from accepting new connections and keeps existing | ||
* connections. This function is asynchronous, the server is finally closed | ||
* when all connections are ended and the server emits a `'close'` event. | ||
* The optional `callback` will be called once the `'close'` event occurs. Unlike | ||
* that event, it will be called with an `Error` as its only argument if the server | ||
* was not open when it was closed. | ||
* @since v0.1.90 | ||
* @param callback Called when the server is closed. | ||
*/ | ||
close(callback?: (err?: Error) => void): this; | ||
/** | ||
* Returns the bound `address`, the address `family` name, and `port` of the server | ||
* as reported by the operating system if listening on an IP socket | ||
* (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. | ||
* | ||
* For a server listening on a pipe or Unix domain socket, the name is returned | ||
* as a string. | ||
* | ||
* ```js | ||
* const server = net.createServer((socket) => { | ||
* socket.end('goodbye\n'); | ||
* }).on('error', (err) => { | ||
* // Handle errors here. | ||
* throw err; | ||
* }); | ||
* | ||
* // Grab an arbitrary unused port. | ||
* server.listen(() => { | ||
* console.log('opened server on', server.address()); | ||
* }); | ||
* ``` | ||
* | ||
* `server.address()` returns `null` before the `'listening'` event has been | ||
* emitted or after calling `server.close()`. | ||
* @since v0.1.90 | ||
*/ | ||
address(): AddressInfo | string | null; | ||
/** | ||
* Asynchronously get the number of concurrent connections on the server. Works | ||
* when sockets were sent to forks. | ||
* | ||
* Callback should take two arguments `err` and `count`. | ||
* @since v0.9.7 | ||
*/ | ||
getConnections(cb: (error: Error | null, count: number) => void): void; | ||
/** | ||
* 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. | ||
* @since v0.9.1 | ||
*/ | ||
ref(): this; | ||
/** | ||
* Calling `unref()` on a server will allow the program to exit if this is the only | ||
* active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. | ||
* @since v0.9.1 | ||
*/ | ||
unref(): this; | ||
/** | ||
* Set this property to reject connections when the server's connection count gets | ||
* high. | ||
* | ||
* It is not recommended to use this option once a socket has been sent to a child | ||
* with `child_process.fork()`. | ||
* @since v0.2.0 | ||
*/ | ||
maxConnections: number; | ||
connections: number; | ||
/** | ||
* Indicates whether or not the server is listening for connections. | ||
* @since v5.7.0 | ||
*/ | ||
listening: boolean; | ||
/** | ||
@@ -222,2 +650,3 @@ * events.EventEmitter | ||
* 4. listening | ||
* 5. drop | ||
*/ | ||
@@ -229,3 +658,3 @@ addListener(event: string, listener: (...args: any[]) => void): this; | ||
addListener(event: "listening", listener: () => void): this; | ||
addListener(event: "drop", listener: (data?: DropArgument) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -236,3 +665,3 @@ emit(event: "close"): boolean; | ||
emit(event: "listening"): boolean; | ||
emit(event: "drop", data?: DropArgument): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -243,3 +672,3 @@ on(event: "close", listener: () => void): this; | ||
on(event: "listening", listener: () => void): this; | ||
on(event: "drop", listener: (data?: DropArgument) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -250,3 +679,3 @@ once(event: "close", listener: () => void): this; | ||
once(event: "listening", listener: () => void): this; | ||
once(event: "drop", listener: (data?: DropArgument) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -257,3 +686,3 @@ prependListener(event: "close", listener: () => void): this; | ||
prependListener(event: "listening", listener: () => void): this; | ||
prependListener(event: "drop", listener: (data?: DropArgument) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -264,25 +693,276 @@ prependOnceListener(event: "close", listener: () => void): this; | ||
prependOnceListener(event: "listening", listener: () => void): this; | ||
prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; | ||
/** | ||
* Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. | ||
* @since v20.5.0 | ||
*/ | ||
[Symbol.asyncDispose](): Promise<void>; | ||
} | ||
type IPVersion = "ipv4" | "ipv6"; | ||
/** | ||
* The `BlockList` object can be used with some network APIs to specify rules for | ||
* disabling inbound or outbound access to specific IP addresses, IP ranges, or | ||
* IP subnets. | ||
* @since v15.0.0, v14.18.0 | ||
*/ | ||
class BlockList { | ||
/** | ||
* Adds a rule to block the given IP address. | ||
* @since v15.0.0, v14.18.0 | ||
* @param address An IPv4 or IPv6 address. | ||
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. | ||
*/ | ||
addAddress(address: string, type?: IPVersion): void; | ||
addAddress(address: SocketAddress): void; | ||
/** | ||
* Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). | ||
* @since v15.0.0, v14.18.0 | ||
* @param start The starting IPv4 or IPv6 address in the range. | ||
* @param end The ending IPv4 or IPv6 address in the range. | ||
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. | ||
*/ | ||
addRange(start: string, end: string, type?: IPVersion): void; | ||
addRange(start: SocketAddress, end: SocketAddress): void; | ||
/** | ||
* Adds a rule to block a range of IP addresses specified as a subnet mask. | ||
* @since v15.0.0, v14.18.0 | ||
* @param net The network IPv4 or IPv6 address. | ||
* @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. | ||
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. | ||
*/ | ||
addSubnet(net: SocketAddress, prefix: number): void; | ||
addSubnet(net: string, prefix: number, type?: IPVersion): void; | ||
/** | ||
* Returns `true` if the given IP address matches any of the rules added to the`BlockList`. | ||
* | ||
* ```js | ||
* const blockList = new net.BlockList(); | ||
* blockList.addAddress('123.123.123.123'); | ||
* blockList.addRange('10.0.0.1', '10.0.0.10'); | ||
* blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); | ||
* | ||
* console.log(blockList.check('123.123.123.123')); // Prints: true | ||
* console.log(blockList.check('10.0.0.3')); // Prints: true | ||
* console.log(blockList.check('222.111.111.222')); // Prints: false | ||
* | ||
* // IPv6 notation for IPv4 addresses works: | ||
* console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true | ||
* console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true | ||
* ``` | ||
* @since v15.0.0, v14.18.0 | ||
* @param address The IP address to check | ||
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. | ||
*/ | ||
check(address: SocketAddress): boolean; | ||
check(address: string, type?: IPVersion): boolean; | ||
} | ||
interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { | ||
timeout?: number; | ||
timeout?: number | undefined; | ||
} | ||
interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { | ||
timeout?: number; | ||
timeout?: number | undefined; | ||
} | ||
type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; | ||
/** | ||
* Creates a new TCP or `IPC` server. | ||
* | ||
* If `allowHalfOpen` is set to `true`, when the other end of the socket | ||
* signals the end of transmission, the server will only send back the end of | ||
* transmission when `socket.end()` is explicitly called. For example, in the | ||
* context of TCP, when a FIN packed is received, a FIN packed is sent | ||
* back only when `socket.end()` is explicitly called. Until then the | ||
* connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. | ||
* | ||
* If `pauseOnConnect` is set to `true`, then the socket associated with each | ||
* incoming connection will be paused, and no data will be read from its handle. | ||
* This allows connections to be passed between processes without any data being | ||
* read by the original process. To begin reading data from a paused socket, call `socket.resume()`. | ||
* | ||
* The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. | ||
* | ||
* Here is an example of a TCP echo server which listens for connections | ||
* on port 8124: | ||
* | ||
* ```js | ||
* const net = require('node:net'); | ||
* const server = net.createServer((c) => { | ||
* // 'connection' listener. | ||
* console.log('client connected'); | ||
* c.on('end', () => { | ||
* console.log('client disconnected'); | ||
* }); | ||
* c.write('hello\r\n'); | ||
* c.pipe(c); | ||
* }); | ||
* server.on('error', (err) => { | ||
* throw err; | ||
* }); | ||
* server.listen(8124, () => { | ||
* console.log('server bound'); | ||
* }); | ||
* ``` | ||
* | ||
* Test this by using `telnet`: | ||
* | ||
* ```bash | ||
* telnet localhost 8124 | ||
* ``` | ||
* | ||
* To listen on the socket `/tmp/echo.sock`: | ||
* | ||
* ```js | ||
* server.listen('/tmp/echo.sock', () => { | ||
* console.log('server bound'); | ||
* }); | ||
* ``` | ||
* | ||
* Use `nc` to connect to a Unix domain socket server: | ||
* | ||
* ```bash | ||
* nc -U /tmp/echo.sock | ||
* ``` | ||
* @since v0.5.0 | ||
* @param connectionListener Automatically set as a listener for the {@link 'connection'} event. | ||
*/ | ||
function createServer(connectionListener?: (socket: Socket) => void): Server; | ||
function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; | ||
function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; | ||
/** | ||
* Aliases to {@link createConnection}. | ||
* | ||
* Possible signatures: | ||
* | ||
* * {@link connect} | ||
* * {@link connect} for `IPC` connections. | ||
* * {@link connect} for TCP connections. | ||
*/ | ||
function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; | ||
function connect(port: number, host?: string, connectionListener?: () => void): Socket; | ||
function connect(path: string, connectionListener?: () => void): Socket; | ||
/** | ||
* A factory function, which creates a new {@link Socket}, | ||
* immediately initiates connection with `socket.connect()`, | ||
* then returns the `net.Socket` that starts the connection. | ||
* | ||
* When the connection is established, a `'connect'` event will be emitted | ||
* on the returned socket. The last parameter `connectListener`, if supplied, | ||
* will be added as a listener for the `'connect'` event **once**. | ||
* | ||
* Possible signatures: | ||
* | ||
* * {@link createConnection} | ||
* * {@link createConnection} for `IPC` connections. | ||
* * {@link createConnection} for TCP connections. | ||
* | ||
* The {@link connect} function is an alias to this function. | ||
*/ | ||
function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; | ||
function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; | ||
function createConnection(path: string, connectionListener?: () => void): Socket; | ||
/** | ||
* Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. | ||
* The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. | ||
* @since v19.4.0 | ||
*/ | ||
function getDefaultAutoSelectFamily(): boolean; | ||
/** | ||
* Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. | ||
* @since v19.4.0 | ||
*/ | ||
function setDefaultAutoSelectFamily(value: boolean): void; | ||
/** | ||
* Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. | ||
* The initial default value is `250`. | ||
* @since v19.8.0 | ||
*/ | ||
function getDefaultAutoSelectFamilyAttemptTimeout(): number; | ||
/** | ||
* Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. | ||
* @since v19.8.0 | ||
*/ | ||
function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; | ||
/** | ||
* Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 | ||
* address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. | ||
* | ||
* ```js | ||
* net.isIP('::1'); // returns 6 | ||
* net.isIP('127.0.0.1'); // returns 4 | ||
* net.isIP('127.000.000.001'); // returns 0 | ||
* net.isIP('127.0.0.1/24'); // returns 0 | ||
* net.isIP('fhqwhgads'); // returns 0 | ||
* ``` | ||
* @since v0.3.0 | ||
*/ | ||
function isIP(input: string): number; | ||
/** | ||
* Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no | ||
* leading zeroes. Otherwise, returns `false`. | ||
* | ||
* ```js | ||
* net.isIPv4('127.0.0.1'); // returns true | ||
* net.isIPv4('127.000.000.001'); // returns false | ||
* net.isIPv4('127.0.0.1/24'); // returns false | ||
* net.isIPv4('fhqwhgads'); // returns false | ||
* ``` | ||
* @since v0.3.0 | ||
*/ | ||
function isIPv4(input: string): boolean; | ||
/** | ||
* Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. | ||
* | ||
* ```js | ||
* net.isIPv6('::1'); // returns true | ||
* net.isIPv6('fhqwhgads'); // returns false | ||
* ``` | ||
* @since v0.3.0 | ||
*/ | ||
function isIPv6(input: string): boolean; | ||
interface SocketAddressInitOptions { | ||
/** | ||
* The network address as either an IPv4 or IPv6 string. | ||
* @default 127.0.0.1 | ||
*/ | ||
address?: string | undefined; | ||
/** | ||
* @default `'ipv4'` | ||
*/ | ||
family?: IPVersion | undefined; | ||
/** | ||
* An IPv6 flow-label used only if `family` is `'ipv6'`. | ||
* @default 0 | ||
*/ | ||
flowlabel?: number | undefined; | ||
/** | ||
* An IP port. | ||
* @default 0 | ||
*/ | ||
port?: number | undefined; | ||
} | ||
/** | ||
* @since v15.14.0, v14.18.0 | ||
*/ | ||
class SocketAddress { | ||
constructor(options: SocketAddressInitOptions); | ||
/** | ||
* Either \`'ipv4'\` or \`'ipv6'\`. | ||
* @since v15.14.0, v14.18.0 | ||
*/ | ||
readonly address: string; | ||
/** | ||
* Either \`'ipv4'\` or \`'ipv6'\`. | ||
* @since v15.14.0, v14.18.0 | ||
*/ | ||
readonly family: IPVersion; | ||
/** | ||
* @since v15.14.0, v14.18.0 | ||
*/ | ||
readonly port: number; | ||
/** | ||
* @since v15.14.0, v14.18.0 | ||
*/ | ||
readonly flowlabel: number; | ||
} | ||
} | ||
declare module "node:net" { | ||
export * from "net"; | ||
} |
286
node/os.d.ts
@@ -0,1 +1,10 @@ | ||
/** | ||
* The `node:os` module provides operating system-related utility methods and | ||
* properties. It can be accessed using: | ||
* | ||
* ```js | ||
* const os = require('node:os'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) | ||
*/ | ||
declare module "os" { | ||
@@ -13,3 +22,2 @@ interface CpuInfo { | ||
} | ||
interface NetworkInterfaceBase { | ||
@@ -22,7 +30,6 @@ address: string; | ||
} | ||
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { | ||
family: "IPv4"; | ||
scopeid?: undefined; | ||
} | ||
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { | ||
@@ -32,3 +39,2 @@ family: "IPv6"; | ||
} | ||
interface UserInfo<T> { | ||
@@ -38,25 +44,208 @@ username: T; | ||
gid: number; | ||
shell: T; | ||
shell: T | null; | ||
homedir: T; | ||
} | ||
type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; | ||
/** | ||
* Returns the host name of the operating system as a string. | ||
* @since v0.3.3 | ||
*/ | ||
function hostname(): string; | ||
/** | ||
* Returns an array containing the 1, 5, and 15 minute load averages. | ||
* | ||
* The load average is a measure of system activity calculated by the operating | ||
* system and expressed as a fractional number. | ||
* | ||
* The load average is a Unix-specific concept. On Windows, the return value is | ||
* always `[0, 0, 0]`. | ||
* @since v0.3.3 | ||
*/ | ||
function loadavg(): number[]; | ||
/** | ||
* Returns the system uptime in number of seconds. | ||
* @since v0.3.3 | ||
*/ | ||
function uptime(): number; | ||
/** | ||
* Returns the amount of free system memory in bytes as an integer. | ||
* @since v0.3.3 | ||
*/ | ||
function freemem(): number; | ||
/** | ||
* Returns the total amount of system memory in bytes as an integer. | ||
* @since v0.3.3 | ||
*/ | ||
function totalmem(): number; | ||
/** | ||
* Returns an array of objects containing information about each logical CPU core. | ||
* The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. | ||
* | ||
* The properties included on each object include: | ||
* | ||
* ```js | ||
* [ | ||
* { | ||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', | ||
* speed: 2926, | ||
* times: { | ||
* user: 252020, | ||
* nice: 0, | ||
* sys: 30340, | ||
* idle: 1070356870, | ||
* irq: 0, | ||
* }, | ||
* }, | ||
* { | ||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', | ||
* speed: 2926, | ||
* times: { | ||
* user: 306960, | ||
* nice: 0, | ||
* sys: 26980, | ||
* idle: 1071569080, | ||
* irq: 0, | ||
* }, | ||
* }, | ||
* { | ||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', | ||
* speed: 2926, | ||
* times: { | ||
* user: 248450, | ||
* nice: 0, | ||
* sys: 21750, | ||
* idle: 1070919370, | ||
* irq: 0, | ||
* }, | ||
* }, | ||
* { | ||
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', | ||
* speed: 2926, | ||
* times: { | ||
* user: 256880, | ||
* nice: 0, | ||
* sys: 19430, | ||
* idle: 1070905480, | ||
* irq: 20, | ||
* }, | ||
* }, | ||
* ] | ||
* ``` | ||
* | ||
* `nice` values are POSIX-only. On Windows, the `nice` values of all processors | ||
* are always 0. | ||
* | ||
* `os.cpus().length` should not be used to calculate the amount of parallelism | ||
* available to an application. Use {@link availableParallelism} for this purpose. | ||
* @since v0.3.3 | ||
*/ | ||
function cpus(): CpuInfo[]; | ||
/** | ||
* Returns an estimate of the default amount of parallelism a program should use. | ||
* Always returns a value greater than zero. | ||
* | ||
* This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). | ||
* @since v19.4.0, v18.14.0 | ||
*/ | ||
function availableParallelism(): number; | ||
/** | ||
* Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it | ||
* returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. | ||
* | ||
* See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information | ||
* about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. | ||
* @since v0.3.3 | ||
*/ | ||
function type(): string; | ||
/** | ||
* Returns the operating system as a string. | ||
* | ||
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See | ||
* [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. | ||
* @since v0.3.3 | ||
*/ | ||
function release(): string; | ||
/** | ||
* Returns an object containing network interfaces that have been assigned a | ||
* network address. | ||
* | ||
* Each key on the returned object identifies a network interface. The associated | ||
* value is an array of objects that each describe an assigned network address. | ||
* | ||
* The properties available on the assigned network address object include: | ||
* | ||
* ```js | ||
* { | ||
* lo: [ | ||
* { | ||
* address: '127.0.0.1', | ||
* netmask: '255.0.0.0', | ||
* family: 'IPv4', | ||
* mac: '00:00:00:00:00:00', | ||
* internal: true, | ||
* cidr: '127.0.0.1/8' | ||
* }, | ||
* { | ||
* address: '::1', | ||
* netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', | ||
* family: 'IPv6', | ||
* mac: '00:00:00:00:00:00', | ||
* scopeid: 0, | ||
* internal: true, | ||
* cidr: '::1/128' | ||
* } | ||
* ], | ||
* eth0: [ | ||
* { | ||
* address: '192.168.1.108', | ||
* netmask: '255.255.255.0', | ||
* family: 'IPv4', | ||
* mac: '01:02:03:0a:0b:0c', | ||
* internal: false, | ||
* cidr: '192.168.1.108/24' | ||
* }, | ||
* { | ||
* address: 'fe80::a00:27ff:fe4e:66a1', | ||
* netmask: 'ffff:ffff:ffff:ffff::', | ||
* family: 'IPv6', | ||
* mac: '01:02:03:0a:0b:0c', | ||
* scopeid: 1, | ||
* internal: false, | ||
* cidr: 'fe80::a00:27ff:fe4e:66a1/64' | ||
* } | ||
* ] | ||
* } | ||
* ``` | ||
* @since v0.6.0 | ||
*/ | ||
function networkInterfaces(): NodeJS.Dict<NetworkInterfaceInfo[]>; | ||
/** | ||
* Returns the string path of the current user's home directory. | ||
* | ||
* On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it | ||
* uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. | ||
* | ||
* On Windows, it uses the `USERPROFILE` environment variable if defined. | ||
* Otherwise it uses the path to the profile directory of the current user. | ||
* @since v2.3.0 | ||
*/ | ||
function homedir(): string; | ||
function userInfo(options: { encoding: 'buffer' }): UserInfo<Buffer>; | ||
/** | ||
* Returns information about the currently effective user. On POSIX platforms, | ||
* this is typically a subset of the password file. The returned object includes | ||
* the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. | ||
* | ||
* The value of `homedir` returned by `os.userInfo()` is provided by the operating | ||
* system. This differs from the result of `os.homedir()`, which queries | ||
* environment variables for the home directory before falling back to the | ||
* operating system response. | ||
* | ||
* Throws a `SystemError` if a user has no `username` or `homedir`. | ||
* @since v6.0.0 | ||
*/ | ||
function userInfo(options: { encoding: "buffer" }): UserInfo<Buffer>; | ||
function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>; | ||
type SignalConstants = { | ||
[key in NodeJS.Signals]: number; | ||
}; | ||
namespace constants { | ||
@@ -214,31 +403,80 @@ const UV_UDP_REUSEADDR: number; | ||
} | ||
const devNull: string; | ||
const EOL: string; | ||
/** | ||
* Returns the operating system CPU architecture for which the Node.js binary was | ||
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. | ||
* | ||
* The return value is equivalent to `process.arch`. | ||
* @since v0.5.0 | ||
*/ | ||
function arch(): string; | ||
/** | ||
* Returns a string identifying the kernel version. | ||
* On POSIX systems, the operating system release is determined by calling | ||
* [uname(3)][]. On Windows, `pRtlGetVersion` is used, and if it is not available, | ||
* `GetVersionExW()` will be used. See | ||
* https://en.wikipedia.org/wiki/Uname#Examples for more information. | ||
* | ||
* On POSIX systems, the operating system release 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. | ||
* @since v13.11.0, v12.17.0 | ||
*/ | ||
function version(): string; | ||
/** | ||
* Returns a string identifying the operating system platform for which | ||
* the Node.js binary was compiled. The value is set at compile time. | ||
* Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. | ||
* | ||
* The return value is equivalent to `process.platform`. | ||
* | ||
* The value `'android'` may also be returned if Node.js is built on the Android | ||
* operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). | ||
* @since v0.5.0 | ||
*/ | ||
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`. | ||
* | ||
* 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. | ||
* @since v18.9.0, v16.18.0 | ||
*/ | ||
function machine(): string; | ||
/** | ||
* Returns the operating system's default directory for temporary files as a | ||
* string. | ||
* @since v0.9.9 | ||
*/ | ||
function tmpdir(): string; | ||
const EOL: string; | ||
/** | ||
* Returns a string identifying the endianness of the CPU for which the Node.js | ||
* binary was compiled. | ||
* | ||
* Possible values are `'BE'` for big endian and `'LE'` for little endian. | ||
* @since v0.9.4 | ||
*/ | ||
function endianness(): "BE" | "LE"; | ||
/** | ||
* Gets the priority of a process. | ||
* Defaults to current process. | ||
* Returns the scheduling priority for the process specified by `pid`. If `pid` is | ||
* not provided or is `0`, the priority of the current process is returned. | ||
* @since v10.10.0 | ||
* @param [pid=0] The process ID to retrieve scheduling priority for. | ||
*/ | ||
function getPriority(pid?: number): number; | ||
/** | ||
* Sets the priority of the current process. | ||
* @param priority Must be in range of -20 to 19 | ||
* Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. | ||
* | ||
* The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows | ||
* priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range | ||
* mapping may cause the return value to be slightly different on Windows. To avoid | ||
* confusion, set `priority` to one of the priority constants. | ||
* | ||
* On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user | ||
* privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. | ||
* @since v10.10.0 | ||
* @param [pid=0] The process ID to set scheduling priority for. | ||
* @param priority The scheduling priority to assign to the process. | ||
*/ | ||
function setPriority(priority: number): void; | ||
/** | ||
* Sets the priority of the process specified process. | ||
* @param priority Must be in range of -20 to 19 | ||
*/ | ||
function setPriority(pid: number, priority: number): void; | ||
} | ||
declare module "node:os" { | ||
export * from "os"; | ||
} |
{ | ||
"name": "@types/node", | ||
"version": "14.14.20", | ||
"description": "TypeScript definitions for Node.js", | ||
"version": "20.9.5", | ||
"description": "TypeScript definitions for node", | ||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", | ||
"license": "MIT", | ||
@@ -9,224 +10,199 @@ "contributors": [ | ||
"name": "Microsoft TypeScript", | ||
"url": "https://github.com/Microsoft", | ||
"githubUsername": "Microsoft" | ||
"githubUsername": "Microsoft", | ||
"url": "https://github.com/Microsoft" | ||
}, | ||
{ | ||
"name": "DefinitelyTyped", | ||
"url": "https://github.com/DefinitelyTyped", | ||
"githubUsername": "DefinitelyTyped" | ||
}, | ||
{ | ||
"name": "Alberto Schiabel", | ||
"url": "https://github.com/jkomyno", | ||
"githubUsername": "jkomyno" | ||
"githubUsername": "jkomyno", | ||
"url": "https://github.com/jkomyno" | ||
}, | ||
{ | ||
"name": "Alexander T.", | ||
"url": "https://github.com/a-tarasyuk", | ||
"githubUsername": "a-tarasyuk" | ||
}, | ||
{ | ||
"name": "Alvis HT Tang", | ||
"url": "https://github.com/alvis", | ||
"githubUsername": "alvis" | ||
"githubUsername": "alvis", | ||
"url": "https://github.com/alvis" | ||
}, | ||
{ | ||
"name": "Andrew Makarov", | ||
"url": "https://github.com/r3nya", | ||
"githubUsername": "r3nya" | ||
"githubUsername": "r3nya", | ||
"url": "https://github.com/r3nya" | ||
}, | ||
{ | ||
"name": "Benjamin Toueg", | ||
"url": "https://github.com/btoueg", | ||
"githubUsername": "btoueg" | ||
"githubUsername": "btoueg", | ||
"url": "https://github.com/btoueg" | ||
}, | ||
{ | ||
"name": "Bruno Scheufler", | ||
"url": "https://github.com/brunoscheufler", | ||
"githubUsername": "brunoscheufler" | ||
}, | ||
{ | ||
"name": "Chigozirim C.", | ||
"url": "https://github.com/smac89", | ||
"githubUsername": "smac89" | ||
"githubUsername": "smac89", | ||
"url": "https://github.com/smac89" | ||
}, | ||
{ | ||
"name": "David Junger", | ||
"url": "https://github.com/touffy", | ||
"githubUsername": "touffy" | ||
"githubUsername": "touffy", | ||
"url": "https://github.com/touffy" | ||
}, | ||
{ | ||
"name": "Deividas Bakanas", | ||
"url": "https://github.com/DeividasBakanas", | ||
"githubUsername": "DeividasBakanas" | ||
"githubUsername": "DeividasBakanas", | ||
"url": "https://github.com/DeividasBakanas" | ||
}, | ||
{ | ||
"name": "Eugene Y. Q. Shen", | ||
"url": "https://github.com/eyqs", | ||
"githubUsername": "eyqs" | ||
"githubUsername": "eyqs", | ||
"url": "https://github.com/eyqs" | ||
}, | ||
{ | ||
"name": "Flarna", | ||
"url": "https://github.com/Flarna", | ||
"githubUsername": "Flarna" | ||
}, | ||
{ | ||
"name": "Hannes Magnusson", | ||
"url": "https://github.com/Hannes-Magnusson-CK", | ||
"githubUsername": "Hannes-Magnusson-CK" | ||
"githubUsername": "Hannes-Magnusson-CK", | ||
"url": "https://github.com/Hannes-Magnusson-CK" | ||
}, | ||
{ | ||
"name": "Hoàng Văn Khải", | ||
"url": "https://github.com/KSXGitHub", | ||
"githubUsername": "KSXGitHub" | ||
}, | ||
{ | ||
"name": "Huw", | ||
"url": "https://github.com/hoo29", | ||
"githubUsername": "hoo29" | ||
"githubUsername": "hoo29", | ||
"url": "https://github.com/hoo29" | ||
}, | ||
{ | ||
"name": "Kelvin Jin", | ||
"url": "https://github.com/kjin", | ||
"githubUsername": "kjin" | ||
"githubUsername": "kjin", | ||
"url": "https://github.com/kjin" | ||
}, | ||
{ | ||
"name": "Klaus Meinhardt", | ||
"url": "https://github.com/ajafff", | ||
"githubUsername": "ajafff" | ||
"githubUsername": "ajafff", | ||
"url": "https://github.com/ajafff" | ||
}, | ||
{ | ||
"name": "Lishude", | ||
"url": "https://github.com/islishude", | ||
"githubUsername": "islishude" | ||
"githubUsername": "islishude", | ||
"url": "https://github.com/islishude" | ||
}, | ||
{ | ||
"name": "Mariusz Wiktorczyk", | ||
"url": "https://github.com/mwiktorczyk", | ||
"githubUsername": "mwiktorczyk" | ||
"githubUsername": "mwiktorczyk", | ||
"url": "https://github.com/mwiktorczyk" | ||
}, | ||
{ | ||
"name": "Mohsen Azimi", | ||
"url": "https://github.com/mohsen1", | ||
"githubUsername": "mohsen1" | ||
"githubUsername": "mohsen1", | ||
"url": "https://github.com/mohsen1" | ||
}, | ||
{ | ||
"name": "Nicolas Even", | ||
"url": "https://github.com/n-e", | ||
"githubUsername": "n-e" | ||
"githubUsername": "n-e", | ||
"url": "https://github.com/n-e" | ||
}, | ||
{ | ||
"name": "Nikita Galkin", | ||
"url": "https://github.com/galkin", | ||
"githubUsername": "galkin" | ||
"githubUsername": "galkin", | ||
"url": "https://github.com/galkin" | ||
}, | ||
{ | ||
"name": "Parambir Singh", | ||
"url": "https://github.com/parambirs", | ||
"githubUsername": "parambirs" | ||
"githubUsername": "parambirs", | ||
"url": "https://github.com/parambirs" | ||
}, | ||
{ | ||
"name": "Sebastian Silbermann", | ||
"url": "https://github.com/eps1lon", | ||
"githubUsername": "eps1lon" | ||
"githubUsername": "eps1lon", | ||
"url": "https://github.com/eps1lon" | ||
}, | ||
{ | ||
"name": "Simon Schick", | ||
"url": "https://github.com/SimonSchick", | ||
"githubUsername": "SimonSchick" | ||
}, | ||
{ | ||
"name": "Thomas den Hollander", | ||
"url": "https://github.com/ThomasdenH", | ||
"githubUsername": "ThomasdenH" | ||
"githubUsername": "ThomasdenH", | ||
"url": "https://github.com/ThomasdenH" | ||
}, | ||
{ | ||
"name": "Wilco Bakker", | ||
"url": "https://github.com/WilcoBakker", | ||
"githubUsername": "WilcoBakker" | ||
"githubUsername": "WilcoBakker", | ||
"url": "https://github.com/WilcoBakker" | ||
}, | ||
{ | ||
"name": "wwwy3y3", | ||
"url": "https://github.com/wwwy3y3", | ||
"githubUsername": "wwwy3y3" | ||
"githubUsername": "wwwy3y3", | ||
"url": "https://github.com/wwwy3y3" | ||
}, | ||
{ | ||
"name": "Samuel Ainsworth", | ||
"url": "https://github.com/samuela", | ||
"githubUsername": "samuela" | ||
"githubUsername": "samuela", | ||
"url": "https://github.com/samuela" | ||
}, | ||
{ | ||
"name": "Kyle Uehlein", | ||
"url": "https://github.com/kuehlein", | ||
"githubUsername": "kuehlein" | ||
"githubUsername": "kuehlein", | ||
"url": "https://github.com/kuehlein" | ||
}, | ||
{ | ||
"name": "Jordi Oliveras Rovira", | ||
"url": "https://github.com/j-oliveras", | ||
"githubUsername": "j-oliveras" | ||
}, | ||
{ | ||
"name": "Thanik Bhongbhibhat", | ||
"url": "https://github.com/bhongy", | ||
"githubUsername": "bhongy" | ||
"githubUsername": "bhongy", | ||
"url": "https://github.com/bhongy" | ||
}, | ||
{ | ||
"name": "Marcin Kopacz", | ||
"url": "https://github.com/chyzwar", | ||
"githubUsername": "chyzwar" | ||
"githubUsername": "chyzwar", | ||
"url": "https://github.com/chyzwar" | ||
}, | ||
{ | ||
"name": "Trivikram Kamat", | ||
"url": "https://github.com/trivikr", | ||
"githubUsername": "trivikr" | ||
"githubUsername": "trivikr", | ||
"url": "https://github.com/trivikr" | ||
}, | ||
{ | ||
"name": "Minh Son Nguyen", | ||
"url": "https://github.com/nguymin4", | ||
"githubUsername": "nguymin4" | ||
}, | ||
{ | ||
"name": "Junxiao Shi", | ||
"url": "https://github.com/yoursunny", | ||
"githubUsername": "yoursunny" | ||
"githubUsername": "yoursunny", | ||
"url": "https://github.com/yoursunny" | ||
}, | ||
{ | ||
"name": "Ilia Baryshnikov", | ||
"url": "https://github.com/qwelias", | ||
"githubUsername": "qwelias" | ||
"githubUsername": "qwelias", | ||
"url": "https://github.com/qwelias" | ||
}, | ||
{ | ||
"name": "ExE Boss", | ||
"url": "https://github.com/ExE-Boss", | ||
"githubUsername": "ExE-Boss" | ||
"githubUsername": "ExE-Boss", | ||
"url": "https://github.com/ExE-Boss" | ||
}, | ||
{ | ||
"name": "Surasak Chaisurin", | ||
"url": "https://github.com/Ryan-Willpower", | ||
"githubUsername": "Ryan-Willpower" | ||
}, | ||
{ | ||
"name": "Piotr Błażejewicz", | ||
"url": "https://github.com/peterblazejewicz", | ||
"githubUsername": "peterblazejewicz" | ||
"githubUsername": "peterblazejewicz", | ||
"url": "https://github.com/peterblazejewicz" | ||
}, | ||
{ | ||
"name": "Anna Henningsen", | ||
"url": "https://github.com/addaleax", | ||
"githubUsername": "addaleax" | ||
"githubUsername": "addaleax", | ||
"url": "https://github.com/addaleax" | ||
}, | ||
{ | ||
"name": "Jason Kwok", | ||
"url": "https://github.com/JasonHK", | ||
"githubUsername": "JasonHK" | ||
"name": "Victor Perin", | ||
"githubUsername": "victorperin", | ||
"url": "https://github.com/victorperin" | ||
}, | ||
{ | ||
"name": "Victor Perin", | ||
"url": "https://github.com/victorperin", | ||
"githubUsername": "victorperin" | ||
"name": "Yongsheng Zhang", | ||
"githubUsername": "ZYSzys", | ||
"url": "https://github.com/ZYSzys" | ||
}, | ||
{ | ||
"name": "Yongsheng Zhang", | ||
"url": "https://github.com/ZYSzys", | ||
"githubUsername": "ZYSzys" | ||
"name": "NodeJS Contributors", | ||
"githubUsername": "NodeJS", | ||
"url": "https://github.com/NodeJS" | ||
}, | ||
{ | ||
"name": "Linus Unnebäck", | ||
"githubUsername": "LinusU", | ||
"url": "https://github.com/LinusU" | ||
}, | ||
{ | ||
"name": "wafuwafu13", | ||
"githubUsername": "wafuwafu13", | ||
"url": "https://github.com/wafuwafu13" | ||
}, | ||
{ | ||
"name": "Matteo Collina", | ||
"githubUsername": "mcollina", | ||
"url": "https://github.com/mcollina" | ||
}, | ||
{ | ||
"name": "Dmitry Semigradsky", | ||
"githubUsername": "Semigradsky", | ||
"url": "https://github.com/Semigradsky" | ||
} | ||
@@ -237,11 +213,6 @@ ], | ||
"typesVersions": { | ||
"<=3.4": { | ||
"<=4.8": { | ||
"*": [ | ||
"ts3.4/*" | ||
"ts4.8/*" | ||
] | ||
}, | ||
"<=3.6": { | ||
"*": [ | ||
"ts3.6/*" | ||
] | ||
} | ||
@@ -255,5 +226,8 @@ }, | ||
"scripts": {}, | ||
"dependencies": {}, | ||
"typesPublisherContentHash": "3ec100758f9a98f40ade23fd5781e233afe6427322127911c2b9a87c70fe396b", | ||
"typeScriptVersion": "3.3" | ||
"dependencies": { | ||
"undici-types": "~5.26.4" | ||
}, | ||
"typesPublisherContentHash": "cd8a86c6bd22ad627d5e5634db95682b25018090a58b6227bd20bc170181834d", | ||
"typeScriptVersion": "4.5", | ||
"nonNpm": true | ||
} |
@@ -0,1 +1,18 @@ | ||
declare module "path/posix" { | ||
import path = require("path"); | ||
export = path; | ||
} | ||
declare module "path/win32" { | ||
import path = require("path"); | ||
export = path; | ||
} | ||
/** | ||
* The `node:path` module provides utilities for working with file and directory | ||
* paths. It can be accessed using: | ||
* | ||
* ```js | ||
* const path = require('node:path'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) | ||
*/ | ||
declare module "path" { | ||
@@ -28,3 +45,2 @@ namespace path { | ||
} | ||
interface FormatInputPathObject { | ||
@@ -34,21 +50,20 @@ /** | ||
*/ | ||
root?: string; | ||
root?: string | undefined; | ||
/** | ||
* The full directory path such as '/home/user/dir' or 'c:\path\dir' | ||
*/ | ||
dir?: string; | ||
dir?: string | undefined; | ||
/** | ||
* The file name including extension (if any) such as 'index.html' | ||
*/ | ||
base?: string; | ||
base?: string | undefined; | ||
/** | ||
* The file extension (if any) such as '.html' | ||
*/ | ||
ext?: string; | ||
ext?: string | undefined; | ||
/** | ||
* The file name without extension (if any) such as 'index' | ||
*/ | ||
name?: string; | ||
name?: string | undefined; | ||
} | ||
interface PlatformPath { | ||
@@ -59,14 +74,15 @@ /** | ||
* | ||
* @param p string path to normalize. | ||
* @param path string path to normalize. | ||
* @throws {TypeError} if `path` is not a string. | ||
*/ | ||
normalize(p: string): string; | ||
normalize(path: string): string; | ||
/** | ||
* Join all arguments together and normalize the resulting path. | ||
* Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. | ||
* | ||
* @param paths paths to join. | ||
* @throws {TypeError} if any of the path segments is not a string. | ||
*/ | ||
join(...paths: string[]): string; | ||
/** | ||
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}. | ||
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}. | ||
* | ||
@@ -80,14 +96,20 @@ * Starting from leftmost {from} parameter, resolves {to} to an absolute path. | ||
* | ||
* @param pathSegments string paths to join. Non-string arguments are ignored. | ||
* @param paths A sequence of paths or path segments. | ||
* @throws {TypeError} if any of the arguments is not a string. | ||
*/ | ||
resolve(...pathSegments: string[]): string; | ||
resolve(...paths: string[]): string; | ||
/** | ||
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. | ||
* | ||
* If the given {path} is a zero-length string, `false` will be returned. | ||
* | ||
* @param path path to test. | ||
* @throws {TypeError} if `path` is not a string. | ||
*/ | ||
isAbsolute(p: string): boolean; | ||
isAbsolute(path: string): boolean; | ||
/** | ||
* Solve the relative path from {from} to {to}. | ||
* Solve the relative path from {from} to {to} based on the current working directory. | ||
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. | ||
* | ||
* @throws {TypeError} if either `from` or `to` is not a string. | ||
*/ | ||
@@ -98,5 +120,6 @@ relative(from: string, to: string): string; | ||
* | ||
* @param p the path to evaluate. | ||
* @param path the path to evaluate. | ||
* @throws {TypeError} if `path` is not a string. | ||
*/ | ||
dirname(p: string): string; | ||
dirname(path: string): string; | ||
/** | ||
@@ -106,33 +129,36 @@ * Return the last portion of a path. Similar to the Unix basename command. | ||
* | ||
* @param p the path to evaluate. | ||
* @param ext optionally, an extension to remove from the result. | ||
* @param path the path to evaluate. | ||
* @param suffix optionally, an extension to remove from the result. | ||
* @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. | ||
*/ | ||
basename(p: string, ext?: string): string; | ||
basename(path: string, suffix?: string): string; | ||
/** | ||
* Return the extension of the path, from the last '.' to end of string in the last portion of the path. | ||
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string | ||
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. | ||
* | ||
* @param p the path to evaluate. | ||
* @param path the path to evaluate. | ||
* @throws {TypeError} if `path` is not a string. | ||
*/ | ||
extname(p: string): string; | ||
extname(path: string): string; | ||
/** | ||
* The platform-specific file separator. '\\' or '/'. | ||
*/ | ||
readonly sep: string; | ||
readonly sep: "\\" | "/"; | ||
/** | ||
* The platform-specific file delimiter. ';' or ':'. | ||
*/ | ||
readonly delimiter: string; | ||
readonly delimiter: ";" | ":"; | ||
/** | ||
* Returns an object from a path string - the opposite of format(). | ||
* | ||
* @param pathString path to evaluate. | ||
* @param path path to evaluate. | ||
* @throws {TypeError} if `path` is not a string. | ||
*/ | ||
parse(p: string): ParsedPath; | ||
parse(path: string): ParsedPath; | ||
/** | ||
* Returns a path string from an object - the opposite of parse(). | ||
* | ||
* @param pathString path to evaluate. | ||
* @param pathObject path to evaluate. | ||
*/ | ||
format(pP: FormatInputPathObject): string; | ||
format(pathObject: FormatInputPathObject): string; | ||
/** | ||
@@ -160,1 +186,13 @@ * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. | ||
} | ||
declare module "node:path" { | ||
import path = require("path"); | ||
export = path; | ||
} | ||
declare module "node:path/posix" { | ||
import path = require("path/posix"); | ||
export = path; | ||
} | ||
declare module "node:path/win32" { | ||
import path = require("path/win32"); | ||
export = path; | ||
} |
@@ -1,81 +0,160 @@ | ||
declare module 'perf_hooks' { | ||
import { AsyncResource } from 'async_hooks'; | ||
type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; | ||
interface PerformanceEntry { | ||
/** | ||
* This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for | ||
* Node.js-specific performance measurements. | ||
* | ||
* Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): | ||
* | ||
* * [High Resolution Time](https://www.w3.org/TR/hr-time-2) | ||
* * [Performance Timeline](https://w3c.github.io/performance-timeline/) | ||
* * [User Timing](https://www.w3.org/TR/user-timing/) | ||
* * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) | ||
* | ||
* ```js | ||
* const { PerformanceObserver, performance } = require('node:perf_hooks'); | ||
* | ||
* const obs = new PerformanceObserver((items) => { | ||
* console.log(items.getEntries()[0].duration); | ||
* performance.clearMarks(); | ||
* }); | ||
* obs.observe({ type: 'measure' }); | ||
* performance.measure('Start to Now'); | ||
* | ||
* performance.mark('A'); | ||
* doSomeLongRunningProcess(() => { | ||
* performance.measure('A to Now', 'A'); | ||
* | ||
* performance.mark('B'); | ||
* performance.measure('A to B', 'A', 'B'); | ||
* }); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) | ||
*/ | ||
declare module "perf_hooks" { | ||
import { AsyncResource } from "node:async_hooks"; | ||
type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; | ||
interface NodeGCPerformanceDetail { | ||
/** | ||
* The total number of milliseconds elapsed for this entry. | ||
* This value will not be meaningful for all Performance Entry types. | ||
* When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies | ||
* the type of garbage collection operation that occurred. | ||
* See perf_hooks.constants for valid values. | ||
*/ | ||
readonly kind?: number | undefined; | ||
/** | ||
* When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` | ||
* property contains additional information about garbage collection operation. | ||
* See perf_hooks.constants for valid values. | ||
*/ | ||
readonly flags?: number | undefined; | ||
} | ||
/** | ||
* The constructor of this class is not exposed to users directly. | ||
* @since v8.5.0 | ||
*/ | ||
class PerformanceEntry { | ||
protected constructor(); | ||
/** | ||
* The total number of milliseconds elapsed for this entry. This value will not | ||
* be meaningful for all Performance Entry types. | ||
* @since v8.5.0 | ||
*/ | ||
readonly duration: number; | ||
/** | ||
* The name of the performance entry. | ||
* @since v8.5.0 | ||
*/ | ||
readonly name: string; | ||
/** | ||
* The high resolution millisecond timestamp marking the starting time of the Performance Entry. | ||
* The high resolution millisecond timestamp marking the starting time of the | ||
* Performance Entry. | ||
* @since v8.5.0 | ||
*/ | ||
readonly startTime: number; | ||
/** | ||
* The type of the performance entry. | ||
* Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. | ||
* The type of the performance entry. It may be one of: | ||
* | ||
* * `'node'` (Node.js only) | ||
* * `'mark'` (available on the Web) | ||
* * `'measure'` (available on the Web) | ||
* * `'gc'` (Node.js only) | ||
* * `'function'` (Node.js only) | ||
* * `'http2'` (Node.js only) | ||
* * `'http'` (Node.js only) | ||
* @since v8.5.0 | ||
*/ | ||
readonly entryType: EntryType; | ||
/** | ||
* When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies | ||
* the type of garbage collection operation that occurred. | ||
* See perf_hooks.constants for valid values. | ||
* Additional detail specific to the `entryType`. | ||
* @since v16.0.0 | ||
*/ | ||
readonly kind?: number; | ||
/** | ||
* When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` | ||
* property contains additional information about garbage collection operation. | ||
* See perf_hooks.constants for valid values. | ||
*/ | ||
readonly flags?: number; | ||
readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. | ||
toJSON(): any; | ||
} | ||
interface PerformanceNodeTiming extends PerformanceEntry { | ||
/** | ||
* Exposes marks created via the `Performance.mark()` method. | ||
* @since v18.2.0, v16.17.0 | ||
*/ | ||
class PerformanceMark extends PerformanceEntry { | ||
readonly duration: 0; | ||
readonly entryType: "mark"; | ||
} | ||
/** | ||
* Exposes measures created via the `Performance.measure()` method. | ||
* | ||
* The constructor of this class is not exposed to users directly. | ||
* @since v18.2.0, v16.17.0 | ||
*/ | ||
class PerformanceMeasure extends PerformanceEntry { | ||
readonly entryType: "measure"; | ||
} | ||
/** | ||
* _This property is an extension by Node.js. It is not available in Web browsers._ | ||
* | ||
* Provides timing details for Node.js itself. The constructor of this class | ||
* is not exposed to users. | ||
* @since v8.5.0 | ||
*/ | ||
class PerformanceNodeTiming extends PerformanceEntry { | ||
/** | ||
* The high resolution millisecond timestamp at which the Node.js process completed bootstrap. | ||
* The high resolution millisecond timestamp at which the Node.js process | ||
* completed bootstrapping. If bootstrapping has not yet finished, the property | ||
* has the value of -1. | ||
* @since v8.5.0 | ||
*/ | ||
readonly bootstrapComplete: number; | ||
/** | ||
* The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. | ||
* If bootstrapping has not yet finished, the property has the value of -1. | ||
* The high resolution millisecond timestamp at which the Node.js environment was | ||
* initialized. | ||
* @since v8.5.0 | ||
*/ | ||
readonly environment: number; | ||
/** | ||
* The high resolution millisecond timestamp at which the Node.js environment was initialized. | ||
* The high resolution millisecond timestamp of the amount of time the event loop | ||
* has been idle within the event loop's event provider (e.g. `epoll_wait`). This | ||
* does not take CPU usage into consideration. If the event loop has not yet | ||
* started (e.g., in the first tick of the main script), the property has the | ||
* value of 0. | ||
* @since v14.10.0, v12.19.0 | ||
*/ | ||
readonly idleTime: number; | ||
/** | ||
* The high resolution millisecond timestamp of the amount of time the event loop has been idle | ||
* within the event loop's event provider (e.g. `epoll_wait`). This does not take CPU usage | ||
* into consideration. If the event loop has not yet started (e.g., in the first tick of the main script), | ||
* the property has the value of 0. | ||
* The high resolution millisecond timestamp at which the Node.js event loop | ||
* exited. If the event loop has not yet exited, the property has the value of -1\. | ||
* It can only have a value of not -1 in a handler of the `'exit'` event. | ||
* @since v8.5.0 | ||
*/ | ||
readonly loopExit: number; | ||
/** | ||
* The high resolution millisecond timestamp at which the Node.js event loop started. | ||
* If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. | ||
* The high resolution millisecond timestamp at which the Node.js event loop | ||
* started. If the event loop has not yet started (e.g., in the first tick of the | ||
* main script), the property has the value of -1. | ||
* @since v8.5.0 | ||
*/ | ||
readonly loopStart: number; | ||
/** | ||
* The high resolution millisecond timestamp at which the V8 platform was initialized. | ||
* The high resolution millisecond timestamp at which the V8 platform was | ||
* initialized. | ||
* @since v8.5.0 | ||
*/ | ||
readonly v8Start: number; | ||
} | ||
interface EventLoopUtilization { | ||
@@ -86,3 +165,47 @@ idle: number; | ||
} | ||
/** | ||
* @param util1 The result of a previous call to eventLoopUtilization() | ||
* @param util2 The result of a previous call to eventLoopUtilization() prior to util1 | ||
*/ | ||
type EventLoopUtilityFunction = ( | ||
util1?: EventLoopUtilization, | ||
util2?: EventLoopUtilization, | ||
) => EventLoopUtilization; | ||
interface MarkOptions { | ||
/** | ||
* Additional optional detail to include with the mark. | ||
*/ | ||
detail?: unknown | undefined; | ||
/** | ||
* An optional timestamp to be used as the mark time. | ||
* @default `performance.now()`. | ||
*/ | ||
startTime?: number | undefined; | ||
} | ||
interface MeasureOptions { | ||
/** | ||
* Additional optional detail to include with the mark. | ||
*/ | ||
detail?: unknown | undefined; | ||
/** | ||
* Duration between start and end times. | ||
*/ | ||
duration?: number | undefined; | ||
/** | ||
* Timestamp to be used as the end time, or a string identifying a previously recorded mark. | ||
*/ | ||
end?: number | string | undefined; | ||
/** | ||
* Timestamp to be used as the start time, or a string identifying a previously recorded mark. | ||
*/ | ||
start?: number | string | undefined; | ||
} | ||
interface TimerifyOptions { | ||
/** | ||
* A histogram object created using | ||
* `perf_hooks.createHistogram()` that will record runtime durations in | ||
* nanoseconds. | ||
*/ | ||
histogram?: RecordableHistogram | undefined; | ||
} | ||
interface Performance { | ||
@@ -95,4 +218,32 @@ /** | ||
clearMarks(name?: string): void; | ||
/** | ||
* If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. | ||
* If name is provided, removes only the named measure. | ||
* @param name | ||
* @since v16.7.0 | ||
*/ | ||
clearMeasures(name?: string): void; | ||
/** | ||
* Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. | ||
* If you are only interested in performance entries of certain types or that have certain names, see | ||
* `performance.getEntriesByType()` and `performance.getEntriesByName()`. | ||
* @since v16.7.0 | ||
*/ | ||
getEntries(): PerformanceEntry[]; | ||
/** | ||
* Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` | ||
* whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. | ||
* @param name | ||
* @param type | ||
* @since v16.7.0 | ||
*/ | ||
getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; | ||
/** | ||
* Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` | ||
* whose `performanceEntry.entryType` is equal to `type`. | ||
* @param type | ||
* @since v16.7.0 | ||
*/ | ||
getEntriesByType(type: EntryType): PerformanceEntry[]; | ||
/** | ||
* Creates a new PerformanceMark entry in the Performance Timeline. | ||
@@ -103,5 +254,5 @@ * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', | ||
* @param name | ||
* @return The PerformanceMark entry that was created | ||
*/ | ||
mark(name?: string): void; | ||
mark(name?: string, options?: MarkOptions): PerformanceMark; | ||
/** | ||
@@ -121,5 +272,6 @@ * Creates a new PerformanceMeasure entry in the Performance Timeline. | ||
* @param endMark | ||
* @return The PerformanceMeasure entry that was created | ||
*/ | ||
measure(name: string, startMark: string, endMark: string): void; | ||
measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; | ||
measure(name: string, options: MeasureOptions): PerformanceMeasure; | ||
/** | ||
@@ -129,3 +281,2 @@ * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. | ||
readonly nodeTiming: PerformanceNodeTiming; | ||
/** | ||
@@ -135,3 +286,2 @@ * @return the current high resolution millisecond timestamp | ||
now(): number; | ||
/** | ||
@@ -141,3 +291,2 @@ * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. | ||
readonly timeOrigin: number; | ||
/** | ||
@@ -148,4 +297,3 @@ * Wraps a function within a new function that measures the running time of the wrapped function. | ||
*/ | ||
timerify<T extends (...optionalParams: any[]) => any>(fn: T): T; | ||
timerify<T extends (...params: any[]) => any>(fn: T, options?: TimerifyOptions): T; | ||
/** | ||
@@ -155,47 +303,179 @@ * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. | ||
* No other CPU idle time is taken into consideration. | ||
* | ||
* @param util1 The result of a previous call to eventLoopUtilization() | ||
* @param util2 The result of a previous call to eventLoopUtilization() prior to util1 | ||
*/ | ||
eventLoopUtilization(util1?: EventLoopUtilization, util2?: EventLoopUtilization): EventLoopUtilization; | ||
eventLoopUtilization: EventLoopUtilityFunction; | ||
} | ||
interface PerformanceObserverEntryList { | ||
/** | ||
* @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. | ||
* Returns a list of `PerformanceEntry` objects in chronological order | ||
* with respect to `performanceEntry.startTime`. | ||
* | ||
* ```js | ||
* const { | ||
* performance, | ||
* PerformanceObserver, | ||
* } = require('node:perf_hooks'); | ||
* | ||
* const obs = new PerformanceObserver((perfObserverList, observer) => { | ||
* console.log(perfObserverList.getEntries()); | ||
* | ||
* * [ | ||
* * PerformanceEntry { | ||
* * name: 'test', | ||
* * entryType: 'mark', | ||
* * startTime: 81.465639, | ||
* * duration: 0 | ||
* * }, | ||
* * PerformanceEntry { | ||
* * name: 'meow', | ||
* * entryType: 'mark', | ||
* * startTime: 81.860064, | ||
* * duration: 0 | ||
* * } | ||
* * ] | ||
* | ||
* performance.clearMarks(); | ||
* performance.clearMeasures(); | ||
* observer.disconnect(); | ||
* }); | ||
* obs.observe({ type: 'mark' }); | ||
* | ||
* performance.mark('test'); | ||
* performance.mark('meow'); | ||
* ``` | ||
* @since v8.5.0 | ||
*/ | ||
getEntries(): PerformanceEntry[]; | ||
/** | ||
* @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime | ||
* whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. | ||
* Returns a list of `PerformanceEntry` objects in chronological order | ||
* with respect to `performanceEntry.startTime` whose `performanceEntry.name` is | ||
* equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. | ||
* | ||
* ```js | ||
* const { | ||
* performance, | ||
* PerformanceObserver, | ||
* } = require('node:perf_hooks'); | ||
* | ||
* const obs = new PerformanceObserver((perfObserverList, observer) => { | ||
* console.log(perfObserverList.getEntriesByName('meow')); | ||
* | ||
* * [ | ||
* * PerformanceEntry { | ||
* * name: 'meow', | ||
* * entryType: 'mark', | ||
* * startTime: 98.545991, | ||
* * duration: 0 | ||
* * } | ||
* * ] | ||
* | ||
* console.log(perfObserverList.getEntriesByName('nope')); // [] | ||
* | ||
* console.log(perfObserverList.getEntriesByName('test', 'mark')); | ||
* | ||
* * [ | ||
* * PerformanceEntry { | ||
* * name: 'test', | ||
* * entryType: 'mark', | ||
* * startTime: 63.518931, | ||
* * duration: 0 | ||
* * } | ||
* * ] | ||
* | ||
* console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] | ||
* | ||
* performance.clearMarks(); | ||
* performance.clearMeasures(); | ||
* observer.disconnect(); | ||
* }); | ||
* obs.observe({ entryTypes: ['mark', 'measure'] }); | ||
* | ||
* performance.mark('test'); | ||
* performance.mark('meow'); | ||
* ``` | ||
* @since v8.5.0 | ||
*/ | ||
getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; | ||
/** | ||
* @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime | ||
* whose performanceEntry.entryType is equal to type. | ||
* Returns a list of `PerformanceEntry` objects in chronological order | ||
* with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. | ||
* | ||
* ```js | ||
* const { | ||
* performance, | ||
* PerformanceObserver, | ||
* } = require('node:perf_hooks'); | ||
* | ||
* const obs = new PerformanceObserver((perfObserverList, observer) => { | ||
* console.log(perfObserverList.getEntriesByType('mark')); | ||
* | ||
* * [ | ||
* * PerformanceEntry { | ||
* * name: 'test', | ||
* * entryType: 'mark', | ||
* * startTime: 55.897834, | ||
* * duration: 0 | ||
* * }, | ||
* * PerformanceEntry { | ||
* * name: 'meow', | ||
* * entryType: 'mark', | ||
* * startTime: 56.350146, | ||
* * duration: 0 | ||
* * } | ||
* * ] | ||
* | ||
* performance.clearMarks(); | ||
* performance.clearMeasures(); | ||
* observer.disconnect(); | ||
* }); | ||
* obs.observe({ type: 'mark' }); | ||
* | ||
* performance.mark('test'); | ||
* performance.mark('meow'); | ||
* ``` | ||
* @since v8.5.0 | ||
*/ | ||
getEntriesByType(type: EntryType): PerformanceEntry[]; | ||
} | ||
type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; | ||
/** | ||
* @since v8.5.0 | ||
*/ | ||
class PerformanceObserver extends AsyncResource { | ||
constructor(callback: PerformanceObserverCallback); | ||
/** | ||
* Disconnects the PerformanceObserver instance from all notifications. | ||
* Disconnects the `PerformanceObserver` instance from all notifications. | ||
* @since v8.5.0 | ||
*/ | ||
disconnect(): void; | ||
/** | ||
* Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. | ||
* When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. | ||
* Property buffered defaults to false. | ||
* @param options | ||
* Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: | ||
* | ||
* ```js | ||
* const { | ||
* performance, | ||
* PerformanceObserver, | ||
* } = require('node:perf_hooks'); | ||
* | ||
* const obs = new PerformanceObserver((list, observer) => { | ||
* // Called once asynchronously. `list` contains three items. | ||
* }); | ||
* obs.observe({ type: 'mark' }); | ||
* | ||
* for (let n = 0; n < 3; n++) | ||
* performance.mark(`test${n}`); | ||
* ``` | ||
* @since v8.5.0 | ||
*/ | ||
observe(options: { entryTypes: ReadonlyArray<EntryType>; buffered?: boolean }): void; | ||
observe( | ||
options: | ||
| { | ||
entryTypes: readonly EntryType[]; | ||
buffered?: boolean | undefined; | ||
} | ||
| { | ||
type: EntryType; | ||
buffered?: boolean | undefined; | ||
}, | ||
): void; | ||
} | ||
namespace constants { | ||
@@ -206,3 +486,2 @@ const NODE_PERFORMANCE_GC_MAJOR: number; | ||
const NODE_PERFORMANCE_GC_WEAKCB: number; | ||
const NODE_PERFORMANCE_GC_FLAGS_NO: number; | ||
@@ -216,5 +495,3 @@ const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; | ||
} | ||
const performance: Performance; | ||
interface EventLoopMonitorOptions { | ||
@@ -226,58 +503,149 @@ /** | ||
*/ | ||
resolution?: number; | ||
resolution?: number | undefined; | ||
} | ||
interface EventLoopDelayMonitor { | ||
interface Histogram { | ||
/** | ||
* Enables the event loop delay sample timer. Returns `true` if the timer was started, `false` if it was already started. | ||
* Returns a `Map` object detailing the accumulated percentile distribution. | ||
* @since v11.10.0 | ||
*/ | ||
enable(): boolean; | ||
readonly percentiles: Map<number, number>; | ||
/** | ||
* Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. | ||
* The number of times the event loop delay exceeded the maximum 1 hour event | ||
* loop delay threshold. | ||
* @since v11.10.0 | ||
*/ | ||
disable(): boolean; | ||
readonly exceeds: number; | ||
/** | ||
* The minimum recorded event loop delay. | ||
* @since v11.10.0 | ||
*/ | ||
readonly min: number; | ||
/** | ||
* The maximum recorded event loop delay. | ||
* @since v11.10.0 | ||
*/ | ||
readonly max: number; | ||
/** | ||
* The mean of the recorded event loop delays. | ||
* @since v11.10.0 | ||
*/ | ||
readonly mean: number; | ||
/** | ||
* The standard deviation of the recorded event loop delays. | ||
* @since v11.10.0 | ||
*/ | ||
readonly stddev: number; | ||
/** | ||
* Resets the collected histogram data. | ||
* @since v11.10.0 | ||
*/ | ||
reset(): void; | ||
/** | ||
* Returns the value at the given percentile. | ||
* @param percentile A percentile value between 1 and 100. | ||
* @since v11.10.0 | ||
* @param percentile A percentile value in the range (0, 100]. | ||
*/ | ||
percentile(percentile: number): number; | ||
} | ||
interface IntervalHistogram extends Histogram { | ||
/** | ||
* A `Map` object detailing the accumulated percentile distribution. | ||
* Enables the update interval timer. Returns `true` if the timer was | ||
* started, `false` if it was already started. | ||
* @since v11.10.0 | ||
*/ | ||
readonly percentiles: Map<number, number>; | ||
enable(): boolean; | ||
/** | ||
* The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. | ||
* Disables the update interval timer. Returns `true` if the timer was | ||
* stopped, `false` if it was already stopped. | ||
* @since v11.10.0 | ||
*/ | ||
readonly exceeds: number; | ||
disable(): boolean; | ||
} | ||
interface RecordableHistogram extends Histogram { | ||
/** | ||
* The minimum recorded event loop delay. | ||
* @since v15.9.0, v14.18.0 | ||
* @param val The amount to record in the histogram. | ||
*/ | ||
readonly min: number; | ||
record(val: number | bigint): void; | ||
/** | ||
* The maximum recorded event loop delay. | ||
* Calculates the amount of time (in nanoseconds) that has passed since the | ||
* previous call to `recordDelta()` and records that amount in the histogram. | ||
* | ||
* ## Examples | ||
* @since v15.9.0, v14.18.0 | ||
*/ | ||
readonly max: number; | ||
recordDelta(): void; | ||
/** | ||
* The mean of the recorded event loop delays. | ||
* Adds the values from `other` to this histogram. | ||
* @since v17.4.0, v16.14.0 | ||
*/ | ||
readonly mean: number; | ||
add(other: RecordableHistogram): void; | ||
} | ||
/** | ||
* _This property is an extension by Node.js. It is not available in Web browsers._ | ||
* | ||
* Creates an `IntervalHistogram` object that samples and reports the event loop | ||
* delay over time. The delays will be reported in nanoseconds. | ||
* | ||
* Using a timer to detect approximate event loop delay works because the | ||
* execution of timers is tied specifically to the lifecycle of the libuv | ||
* event loop. That is, a delay in the loop will cause a delay in the execution | ||
* of the timer, and those delays are specifically what this API is intended to | ||
* detect. | ||
* | ||
* ```js | ||
* const { monitorEventLoopDelay } = require('node:perf_hooks'); | ||
* const h = monitorEventLoopDelay({ resolution: 20 }); | ||
* h.enable(); | ||
* // Do something. | ||
* h.disable(); | ||
* console.log(h.min); | ||
* console.log(h.max); | ||
* console.log(h.mean); | ||
* console.log(h.stddev); | ||
* console.log(h.percentiles); | ||
* console.log(h.percentile(50)); | ||
* console.log(h.percentile(99)); | ||
* ``` | ||
* @since v11.10.0 | ||
*/ | ||
function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; | ||
interface CreateHistogramOptions { | ||
/** | ||
* The standard deviation of the recorded event loop delays. | ||
* The minimum recordable value. Must be an integer value greater than 0. | ||
* @default 1 | ||
*/ | ||
readonly stddev: number; | ||
min?: number | bigint | undefined; | ||
/** | ||
* The maximum recordable value. Must be an integer value greater than min. | ||
* @default Number.MAX_SAFE_INTEGER | ||
*/ | ||
max?: number | bigint | undefined; | ||
/** | ||
* The number of accuracy digits. Must be a number between 1 and 5. | ||
* @default 3 | ||
*/ | ||
figures?: number | undefined; | ||
} | ||
function monitorEventLoopDelay(options?: EventLoopMonitorOptions): EventLoopDelayMonitor; | ||
/** | ||
* Returns a `RecordableHistogram`. | ||
* @since v15.9.0, v14.18.0 | ||
*/ | ||
function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; | ||
import { performance as _performance } from "perf_hooks"; | ||
global { | ||
/** | ||
* `performance` is a global reference for `require('perf_hooks').performance` | ||
* https://nodejs.org/api/globals.html#performance | ||
* @since v16.0.0 | ||
*/ | ||
var performance: typeof globalThis extends { | ||
onmessage: any; | ||
performance: infer T; | ||
} ? T | ||
: typeof _performance; | ||
} | ||
} | ||
declare module "node:perf_hooks" { | ||
export * from "perf_hooks"; | ||
} |
@@ -0,32 +1,78 @@ | ||
/** | ||
* **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users | ||
* currently depending on the `punycode` module should switch to using the | ||
* userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL | ||
* encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. | ||
* | ||
* The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It | ||
* can be accessed using: | ||
* | ||
* ```js | ||
* const punycode = require('punycode'); | ||
* ``` | ||
* | ||
* [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is | ||
* primarily intended for use in Internationalized Domain Names. Because host | ||
* names in URLs are limited to ASCII characters only, Domain Names that contain | ||
* non-ASCII characters must be converted into ASCII using the Punycode scheme. | ||
* For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent | ||
* to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. | ||
* | ||
* The `punycode` module provides a simple implementation of the Punycode standard. | ||
* | ||
* The `punycode` module is a third-party dependency used by Node.js and | ||
* 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/v20.2.0/lib/punycode.js) | ||
*/ | ||
declare module "punycode" { | ||
/** | ||
* @deprecated since v7.0.0 | ||
* The version of the punycode module bundled in Node.js is being deprecated. | ||
* In a future major version of Node.js this module will be removed. | ||
* Users currently depending on the punycode module should switch to using | ||
* the userland-provided Punycode.js module instead. | ||
* The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only | ||
* characters to the equivalent string of Unicode codepoints. | ||
* | ||
* ```js | ||
* punycode.decode('maana-pta'); // 'mañana' | ||
* punycode.decode('--dqo34k'); // '☃-⌘' | ||
* ``` | ||
* @since v0.5.1 | ||
*/ | ||
function decode(string: string): string; | ||
/** | ||
* @deprecated since v7.0.0 | ||
* The version of the punycode module bundled in Node.js is being deprecated. | ||
* In a future major version of Node.js this module will be removed. | ||
* Users currently depending on the punycode module should switch to using | ||
* the userland-provided Punycode.js module instead. | ||
* The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. | ||
* | ||
* ```js | ||
* punycode.encode('mañana'); // 'maana-pta' | ||
* punycode.encode('☃-⌘'); // '--dqo34k' | ||
* ``` | ||
* @since v0.5.1 | ||
*/ | ||
function encode(string: string): string; | ||
/** | ||
* @deprecated since v7.0.0 | ||
* The version of the punycode module bundled in Node.js is being deprecated. | ||
* In a future major version of Node.js this module will be removed. | ||
* Users currently depending on the punycode module should switch to using | ||
* the userland-provided Punycode.js module instead. | ||
* The `punycode.toUnicode()` method converts a string representing a domain name | ||
* containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be | ||
* converted. | ||
* | ||
* ```js | ||
* // decode domain names | ||
* punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' | ||
* punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' | ||
* punycode.toUnicode('example.com'); // 'example.com' | ||
* ``` | ||
* @since v0.6.1 | ||
*/ | ||
function toUnicode(domain: string): string; | ||
/** | ||
* @deprecated since v7.0.0 | ||
* The version of the punycode module bundled in Node.js is being deprecated. | ||
* In a future major version of Node.js this module will be removed. | ||
* Users currently depending on the punycode module should switch to using | ||
* the userland-provided Punycode.js module instead. | ||
* The `punycode.toASCII()` method converts a Unicode string representing an | ||
* Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the | ||
* domain name will be converted. Calling `punycode.toASCII()` on a string that | ||
* already only contains ASCII characters will have no effect. | ||
* | ||
* ```js | ||
* // encode domain names | ||
* punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' | ||
* punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' | ||
* punycode.toASCII('example.com'); // 'example.com' | ||
* ``` | ||
* @since v0.6.1 | ||
*/ | ||
@@ -58,3 +104,3 @@ function toASCII(domain: string): string; | ||
*/ | ||
encode(codePoints: ReadonlyArray<number>): string; | ||
encode(codePoints: readonly number[]): string; | ||
} | ||
@@ -70,1 +116,4 @@ /** | ||
} | ||
declare module "node:punycode" { | ||
export * from "punycode"; | ||
} |
@@ -0,17 +1,103 @@ | ||
/** | ||
* The `node:querystring` module provides utilities for parsing and formatting URL | ||
* query strings. It can be accessed using: | ||
* | ||
* ```js | ||
* const querystring = require('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/v20.2.0/lib/querystring.js) | ||
*/ | ||
declare module "querystring" { | ||
interface StringifyOptions { | ||
encodeURIComponent?: (str: string) => string; | ||
encodeURIComponent?: ((str: string) => string) | undefined; | ||
} | ||
interface ParseOptions { | ||
maxKeys?: number; | ||
decodeURIComponent?: (str: string) => string; | ||
maxKeys?: number | undefined; | ||
decodeURIComponent?: ((str: string) => string) | undefined; | ||
} | ||
interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> { } | ||
interface ParsedUrlQueryInput extends NodeJS.Dict<string | number | boolean | ReadonlyArray<string> | ReadonlyArray<number> | ReadonlyArray<boolean> | null> { | ||
} | ||
interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> {} | ||
interface ParsedUrlQueryInput extends | ||
NodeJS.Dict< | ||
| string | ||
| number | ||
| boolean | ||
| readonly string[] | ||
| readonly number[] | ||
| readonly boolean[] | ||
| null | ||
> | ||
{} | ||
/** | ||
* The `querystring.stringify()` method produces a URL query string from a | ||
* given `obj` by iterating through the object's "own properties". | ||
* | ||
* It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | | ||
* [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | | ||
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | | ||
* [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | | ||
* [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | | ||
* [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | | ||
* [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | | ||
* [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to | ||
* empty strings. | ||
* | ||
* ```js | ||
* querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); | ||
* // Returns 'foo=bar&baz=qux&baz=quux&corge=' | ||
* | ||
* querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); | ||
* // Returns 'foo:bar;baz:qux' | ||
* ``` | ||
* | ||
* By default, characters requiring percent-encoding within the query string will | ||
* be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: | ||
* | ||
* ```js | ||
* // Assuming gbkEncodeURIComponent function already exists, | ||
* | ||
* querystring.stringify({ w: '中文', foo: 'bar' }, null, null, | ||
* { encodeURIComponent: gbkEncodeURIComponent }); | ||
* ``` | ||
* @since v0.1.25 | ||
* @param obj The object to serialize into a URL query string | ||
* @param [sep='&'] The substring used to delimit key and value pairs in the query string. | ||
* @param [eq='='] . The substring used to delimit keys and values in the query string. | ||
*/ | ||
function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; | ||
/** | ||
* The `querystring.parse()` method parses a URL query string (`str`) into a | ||
* collection of key and value pairs. | ||
* | ||
* For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: | ||
* | ||
* ```js | ||
* { | ||
* foo: 'bar', | ||
* abc: ['xyz', '123'] | ||
* } | ||
* ``` | ||
* | ||
* The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, | ||
* `obj.hasOwnProperty()`, and others | ||
* are not defined and _will not work_. | ||
* | ||
* By default, percent-encoded characters within the query string will be assumed | ||
* to use UTF-8 encoding. If an alternative character encoding is used, then an | ||
* alternative `decodeURIComponent` option will need to be specified: | ||
* | ||
* ```js | ||
* // Assuming gbkDecodeURIComponent function already exists... | ||
* | ||
* querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, | ||
* { decodeURIComponent: gbkDecodeURIComponent }); | ||
* ``` | ||
* @since v0.1.25 | ||
* @param str The URL query string to parse | ||
* @param [sep='&'] The substring used to delimit key and value pairs in the query string. | ||
* @param [eq='='] . The substring used to delimit keys and values in the query string. | ||
*/ | ||
function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; | ||
@@ -26,4 +112,31 @@ /** | ||
const decode: typeof parse; | ||
/** | ||
* The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL | ||
* query strings. | ||
* | ||
* The `querystring.escape()` method is used by `querystring.stringify()` and is | ||
* generally not expected to be used directly. It is exported primarily to allow | ||
* application code to provide a replacement percent-encoding implementation if | ||
* necessary by assigning `querystring.escape` to an alternative function. | ||
* @since v0.1.25 | ||
*/ | ||
function escape(str: string): string; | ||
/** | ||
* The `querystring.unescape()` method performs decoding of URL percent-encoded | ||
* characters on the given `str`. | ||
* | ||
* The `querystring.unescape()` method is used by `querystring.parse()` and is | ||
* generally not expected to be used directly. It is exported primarily to allow | ||
* application code to provide a replacement decoding implementation if | ||
* necessary by assigning `querystring.unescape` to an alternative function. | ||
* | ||
* By default, the `querystring.unescape()` method will attempt to use the | ||
* JavaScript built-in `decodeURIComponent()` method to decode. If that fails, | ||
* a safer equivalent that does not throw on malformed URLs will be used. | ||
* @since v0.1.25 | ||
*/ | ||
function unescape(str: string): string; | ||
} | ||
declare module "node:querystring" { | ||
export * from "querystring"; | ||
} |
@@ -0,23 +1,96 @@ | ||
/** | ||
* The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. | ||
* | ||
* To use the promise-based APIs: | ||
* | ||
* ```js | ||
* import * as readline from 'node:readline/promises'; | ||
* ``` | ||
* | ||
* To use the callback and sync APIs: | ||
* | ||
* ```js | ||
* import * as readline from 'node:readline'; | ||
* ``` | ||
* | ||
* The following simple example illustrates the basic use of the `node:readline`module. | ||
* | ||
* ```js | ||
* import * as readline from 'node:readline/promises'; | ||
* import { stdin as input, stdout as output } from 'node:process'; | ||
* | ||
* const rl = readline.createInterface({ input, output }); | ||
* | ||
* const answer = await rl.question('What do you think of Node.js? '); | ||
* | ||
* console.log(`Thank you for your valuable feedback: ${answer}`); | ||
* | ||
* rl.close(); | ||
* ``` | ||
* | ||
* 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/v20.2.0/lib/readline.js) | ||
*/ | ||
declare module "readline" { | ||
import * as events from "events"; | ||
import * as stream from "stream"; | ||
interface Key { | ||
sequence?: string; | ||
name?: string; | ||
ctrl?: boolean; | ||
meta?: boolean; | ||
shift?: boolean; | ||
import { Abortable, EventEmitter } from "node:events"; | ||
import * as promises from "node:readline/promises"; | ||
export { promises }; | ||
export interface Key { | ||
sequence?: string | undefined; | ||
name?: string | undefined; | ||
ctrl?: boolean | undefined; | ||
meta?: boolean | undefined; | ||
shift?: boolean | undefined; | ||
} | ||
class Interface extends events.EventEmitter { | ||
/** | ||
* Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a | ||
* single `input` `Readable` stream and a single `output` `Writable` 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 { | ||
readonly terminal: boolean; | ||
// Need direct access to line/cursor data, for use in external processes | ||
// see: https://github.com/nodejs/node/issues/30347 | ||
/** The current input data */ | ||
/** | ||
* The current input data being processed by node. | ||
* | ||
* This can be used when collecting input from a TTY stream to retrieve the | ||
* current value that has been processed thus far, prior to the `line` event | ||
* being emitted. Once the `line` event has been emitted, this property will | ||
* be an empty string. | ||
* | ||
* Be aware that modifying the value during the instance runtime may have | ||
* unintended consequences if `rl.cursor` is not also controlled. | ||
* | ||
* **If not using a TTY stream for input, use the `'line'` event.** | ||
* | ||
* One possible use case would be as follows: | ||
* | ||
* ```js | ||
* const values = ['lorem ipsum', 'dolor sit amet']; | ||
* const rl = readline.createInterface(process.stdin); | ||
* const showResults = debounce(() => { | ||
* console.log( | ||
* '\n', | ||
* values.filter((val) => val.startsWith(rl.line)).join(' '), | ||
* ); | ||
* }, 300); | ||
* process.stdin.on('keypress', (c, k) => { | ||
* showResults(); | ||
* }); | ||
* ``` | ||
* @since v0.1.98 | ||
*/ | ||
readonly line: string; | ||
/** The current cursor position in the input line */ | ||
/** | ||
* The cursor position relative to `rl.line`. | ||
* | ||
* This will track where the current cursor lands in the input string, when | ||
* reading input from a TTY stream. The position of cursor determines the | ||
* portion of the input string that will be modified as input is processed, | ||
* as well as the column where the terminal caret will be rendered. | ||
* @since v0.1.98 | ||
*/ | ||
readonly cursor: number; | ||
/** | ||
@@ -29,5 +102,10 @@ * NOTE: According to the documentation: | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor | ||
*/ | ||
protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); | ||
protected constructor( | ||
input: NodeJS.ReadableStream, | ||
output?: NodeJS.WritableStream, | ||
completer?: Completer | AsyncCompleter, | ||
terminal?: boolean, | ||
); | ||
/** | ||
@@ -39,21 +117,127 @@ * NOTE: According to the documentation: | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor | ||
*/ | ||
protected constructor(options: ReadLineOptions); | ||
/** | ||
* The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. | ||
* @since v15.3.0, v14.17.0 | ||
* @return the current prompt string | ||
*/ | ||
getPrompt(): string; | ||
/** | ||
* The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. | ||
* @since v0.1.98 | ||
*/ | ||
setPrompt(prompt: string): void; | ||
/** | ||
* The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new | ||
* location at which to provide input. | ||
* | ||
* When called, `rl.prompt()` will resume the `input` stream if it has been | ||
* paused. | ||
* | ||
* If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. | ||
* @since v0.1.98 | ||
* @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. | ||
*/ | ||
prompt(preserveCursor?: boolean): void; | ||
/** | ||
* The `rl.question()` method displays the `query` by writing it to the `output`, | ||
* waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. | ||
* | ||
* When called, `rl.question()` will resume the `input` stream if it has been | ||
* paused. | ||
* | ||
* If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. | ||
* | ||
* The `callback` function passed to `rl.question()` does not follow the typical | ||
* pattern of accepting an `Error` object or `null` as the first argument. | ||
* The `callback` is called with the provided answer as the only argument. | ||
* | ||
* An error will be thrown if calling `rl.question()` after `rl.close()`. | ||
* | ||
* Example usage: | ||
* | ||
* ```js | ||
* rl.question('What is your favorite food? ', (answer) => { | ||
* console.log(`Oh, so your favorite food is ${answer}`); | ||
* }); | ||
* ``` | ||
* | ||
* Using an `AbortController` to cancel a question. | ||
* | ||
* ```js | ||
* const ac = new AbortController(); | ||
* const signal = ac.signal; | ||
* | ||
* rl.question('What is your favorite food? ', { signal }, (answer) => { | ||
* console.log(`Oh, so your favorite food is ${answer}`); | ||
* }); | ||
* | ||
* signal.addEventListener('abort', () => { | ||
* console.log('The food question timed out'); | ||
* }, { once: true }); | ||
* | ||
* setTimeout(() => ac.abort(), 10000); | ||
* ``` | ||
* @since v0.3.3 | ||
* @param query A statement or query to write to `output`, prepended to the prompt. | ||
* @param callback A callback function that is invoked with the user's input in response to the `query`. | ||
*/ | ||
question(query: string, callback: (answer: string) => void): void; | ||
question(query: string, options: Abortable, callback: (answer: string) => void): void; | ||
/** | ||
* The `rl.pause()` method pauses the `input` stream, allowing it to be resumed | ||
* later if necessary. | ||
* | ||
* Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. | ||
* @since v0.3.4 | ||
*/ | ||
pause(): this; | ||
/** | ||
* The `rl.resume()` method resumes the `input` stream if it has been paused. | ||
* @since v0.3.4 | ||
*/ | ||
resume(): this; | ||
/** | ||
* The `rl.close()` method closes the `Interface` instance and | ||
* relinquishes control over the `input` and `output` streams. When called, | ||
* the `'close'` event will be emitted. | ||
* | ||
* Calling `rl.close()` does not immediately stop other events (including `'line'`) | ||
* from being emitted by the `Interface` instance. | ||
* @since v0.1.98 | ||
*/ | ||
close(): 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 | ||
* a `TTY` text terminal. See `TTY keybindings` for a list of key | ||
* combinations. | ||
* | ||
* If `key` is specified, `data` is ignored. | ||
* | ||
* When called, `rl.write()` will resume the `input` stream if it has been | ||
* paused. | ||
* | ||
* If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. | ||
* | ||
* ```js | ||
* rl.write('Delete this!'); | ||
* // Simulate Ctrl+U to delete the line written previously | ||
* rl.write(null, { ctrl: true, name: 'u' }); | ||
* ``` | ||
* | ||
* The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. | ||
* @since v0.1.98 | ||
*/ | ||
write(data: string | Buffer, key?: Key): void; | ||
write(data: undefined | null | string | Buffer, key: Key): void; | ||
/** | ||
* Returns the real position of the cursor in relation to the input | ||
* prompt + string. Long input (wrapping) strings, as well as multiple | ||
* prompt + string. Long input (wrapping) strings, as well as multiple | ||
* line prompts are included in the calculations. | ||
* @since v13.5.0, v12.16.0 | ||
*/ | ||
getCursorPos(): CursorPos; | ||
/** | ||
@@ -68,4 +252,4 @@ * events.EventEmitter | ||
* 7. SIGTSTP | ||
* 8. history | ||
*/ | ||
addListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -79,3 +263,3 @@ addListener(event: "close", listener: () => void): this; | ||
addListener(event: "SIGTSTP", listener: () => void): this; | ||
addListener(event: "history", listener: (history: string[]) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -89,3 +273,3 @@ emit(event: "close"): boolean; | ||
emit(event: "SIGTSTP"): boolean; | ||
emit(event: "history", history: string[]): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -99,3 +283,3 @@ on(event: "close", listener: () => void): this; | ||
on(event: "SIGTSTP", listener: () => void): this; | ||
on(event: "history", listener: (history: string[]) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -109,3 +293,3 @@ once(event: "close", listener: () => void): this; | ||
once(event: "SIGTSTP", listener: () => void): this; | ||
once(event: "history", listener: (history: string[]) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -119,3 +303,3 @@ prependListener(event: "close", listener: () => void): this; | ||
prependListener(event: "SIGTSTP", listener: () => void): this; | ||
prependListener(event: "history", listener: (history: string[]) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -129,52 +313,236 @@ prependOnceListener(event: "close", listener: () => void): this; | ||
prependOnceListener(event: "SIGTSTP", listener: () => void): this; | ||
prependOnceListener(event: "history", listener: (history: string[]) => void): this; | ||
[Symbol.asyncIterator](): AsyncIterableIterator<string>; | ||
} | ||
type ReadLine = Interface; // type forwarded for backwards compatiblity | ||
type Completer = (line: string) => CompleterResult; | ||
type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => any; | ||
type CompleterResult = [string[], string]; | ||
interface ReadLineOptions { | ||
export type ReadLine = Interface; // type forwarded for backwards compatibility | ||
export type Completer = (line: string) => CompleterResult; | ||
export type AsyncCompleter = ( | ||
line: string, | ||
callback: (err?: null | Error, result?: CompleterResult) => void, | ||
) => void; | ||
export type CompleterResult = [string[], string]; | ||
export interface ReadLineOptions { | ||
input: NodeJS.ReadableStream; | ||
output?: NodeJS.WritableStream; | ||
completer?: Completer | AsyncCompleter; | ||
terminal?: boolean; | ||
historySize?: number; | ||
prompt?: string; | ||
crlfDelay?: number; | ||
removeHistoryDuplicates?: boolean; | ||
escapeCodeTimeout?: number; | ||
tabSize?: number; | ||
output?: NodeJS.WritableStream | undefined; | ||
completer?: Completer | AsyncCompleter | undefined; | ||
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. | ||
* @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. | ||
* @default false | ||
*/ | ||
removeHistoryDuplicates?: boolean | undefined; | ||
escapeCodeTimeout?: number | undefined; | ||
tabSize?: number | undefined; | ||
} | ||
function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; | ||
function createInterface(options: ReadLineOptions): Interface; | ||
function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; | ||
type Direction = -1 | 0 | 1; | ||
interface CursorPos { | ||
/** | ||
* The `readline.createInterface()` method creates a new `readline.Interface`instance. | ||
* | ||
* ```js | ||
* const readline = require('node:readline'); | ||
* const rl = readline.createInterface({ | ||
* input: process.stdin, | ||
* output: process.stdout, | ||
* }); | ||
* ``` | ||
* | ||
* Once the `readline.Interface` instance is created, the most common case is to | ||
* listen for the `'line'` event: | ||
* | ||
* ```js | ||
* rl.on('line', (line) => { | ||
* console.log(`Received: ${line}`); | ||
* }); | ||
* ``` | ||
* | ||
* If `terminal` is `true` for this instance then the `output` stream will get | ||
* the best compatibility if it defines an `output.columns` property and emits | ||
* a `'resize'` event on the `output` if or when the columns ever change | ||
* (`process.stdout` does this automatically when it is a TTY). | ||
* | ||
* When creating a `readline.Interface` using `stdin` as input, the program | ||
* will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without | ||
* waiting for user input, call `process.stdin.unref()`. | ||
* @since v0.1.98 | ||
*/ | ||
export function createInterface( | ||
input: NodeJS.ReadableStream, | ||
output?: NodeJS.WritableStream, | ||
completer?: Completer | AsyncCompleter, | ||
terminal?: boolean, | ||
): Interface; | ||
export function createInterface(options: ReadLineOptions): Interface; | ||
/** | ||
* The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. | ||
* | ||
* Optionally, `interface` specifies a `readline.Interface` instance for which | ||
* autocompletion is disabled when copy-pasted input is detected. | ||
* | ||
* If the `stream` is a `TTY`, then it must be in raw mode. | ||
* | ||
* This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop | ||
* the `input` from emitting `'keypress'` events. | ||
* | ||
* ```js | ||
* readline.emitKeypressEvents(process.stdin); | ||
* if (process.stdin.isTTY) | ||
* process.stdin.setRawMode(true); | ||
* ``` | ||
* | ||
* ## Example: Tiny CLI | ||
* | ||
* The following example illustrates the use of `readline.Interface` class to | ||
* implement a small command-line interface: | ||
* | ||
* ```js | ||
* const readline = require('node:readline'); | ||
* const rl = readline.createInterface({ | ||
* input: process.stdin, | ||
* output: process.stdout, | ||
* prompt: 'OHAI> ', | ||
* }); | ||
* | ||
* rl.prompt(); | ||
* | ||
* rl.on('line', (line) => { | ||
* switch (line.trim()) { | ||
* case 'hello': | ||
* console.log('world!'); | ||
* break; | ||
* default: | ||
* console.log(`Say what? I might have heard '${line.trim()}'`); | ||
* break; | ||
* } | ||
* rl.prompt(); | ||
* }).on('close', () => { | ||
* console.log('Have a great day!'); | ||
* process.exit(0); | ||
* }); | ||
* ``` | ||
* | ||
* ## Example: Read file stream line-by-Line | ||
* | ||
* A common use case for `readline` is to consume an input file one line at a | ||
* time. The easiest way to do so is leveraging the `fs.ReadStream` API as | ||
* well as a `for await...of` loop: | ||
* | ||
* ```js | ||
* const fs = require('node:fs'); | ||
* const readline = require('node:readline'); | ||
* | ||
* async function processLineByLine() { | ||
* const fileStream = fs.createReadStream('input.txt'); | ||
* | ||
* const rl = readline.createInterface({ | ||
* input: fileStream, | ||
* crlfDelay: Infinity, | ||
* }); | ||
* // Note: we use the crlfDelay option to recognize all instances of CR LF | ||
* // ('\r\n') in input.txt as a single line break. | ||
* | ||
* for await (const line of rl) { | ||
* // Each line in input.txt will be successively available here as `line`. | ||
* console.log(`Line from file: ${line}`); | ||
* } | ||
* } | ||
* | ||
* processLineByLine(); | ||
* ``` | ||
* | ||
* Alternatively, one could use the `'line'` event: | ||
* | ||
* ```js | ||
* const fs = require('node:fs'); | ||
* const readline = require('node:readline'); | ||
* | ||
* const rl = readline.createInterface({ | ||
* input: fs.createReadStream('sample.txt'), | ||
* crlfDelay: Infinity, | ||
* }); | ||
* | ||
* rl.on('line', (line) => { | ||
* console.log(`Line from file: ${line}`); | ||
* }); | ||
* ``` | ||
* | ||
* 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'); | ||
* | ||
* (async function processLineByLine() { | ||
* try { | ||
* const rl = createInterface({ | ||
* input: createReadStream('big-file.txt'), | ||
* crlfDelay: Infinity, | ||
* }); | ||
* | ||
* rl.on('line', (line) => { | ||
* // Process the line. | ||
* }); | ||
* | ||
* await once(rl, 'close'); | ||
* | ||
* console.log('File processed.'); | ||
* } catch (err) { | ||
* console.error(err); | ||
* } | ||
* })(); | ||
* ``` | ||
* @since v0.7.7 | ||
*/ | ||
export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; | ||
export type Direction = -1 | 0 | 1; | ||
export interface CursorPos { | ||
rows: number; | ||
cols: number; | ||
} | ||
/** | ||
* Clears the current line of this WriteStream in a direction identified by `dir`. | ||
* The `readline.clearLine()` method clears current line of given `TTY` stream | ||
* in a specified direction identified by `dir`. | ||
* @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`. | ||
*/ | ||
function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; | ||
export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; | ||
/** | ||
* Clears this `WriteStream` from the current cursor down. | ||
* The `readline.clearScreenDown()` method clears the given `TTY` stream from | ||
* the current position of the cursor down. | ||
* @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`. | ||
*/ | ||
function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; | ||
export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; | ||
/** | ||
* Moves this WriteStream's cursor to the specified position. | ||
* The `readline.cursorTo()` method moves cursor to the specified position in a | ||
* given `TTY` `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`. | ||
*/ | ||
function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; | ||
export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; | ||
/** | ||
* Moves this WriteStream's cursor relative to its current position. | ||
* The `readline.moveCursor()` method moves the cursor _relative_ to its current | ||
* position in a given `TTY` `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`. | ||
*/ | ||
function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; | ||
export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; | ||
} | ||
declare module "node:readline" { | ||
export * from "readline"; | ||
} |
@@ -5,3 +5,3 @@ # Installation | ||
# Summary | ||
This package contains type definitions for Node.js (http://nodejs.org/). | ||
This package contains type definitions for node (https://nodejs.org/). | ||
@@ -12,7 +12,6 @@ # Details | ||
### Additional Details | ||
* Last updated: Mon, 04 Jan 2021 20:50:23 GMT | ||
* Dependencies: none | ||
* Global values: `Buffer`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout` | ||
* Last updated: Thu, 23 Nov 2023 21:35:40 GMT | ||
* Dependencies: [undici-types](https://npmjs.com/package/undici-types) | ||
# Credits | ||
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alexander T.](https://github.com/a-tarasyuk), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Bruno Scheufler](https://github.com/brunoscheufler), [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), [Flarna](https://github.com/Flarna), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [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), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [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), [Jordi Oliveras Rovira](https://github.com/j-oliveras), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Jason Kwok](https://github.com/JasonHK), [Victor Perin](https://github.com/victorperin), and [Yongsheng Zhang](https://github.com/ZYSzys). | ||
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), [Nicolas Even](https://github.com/n-e), [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). |
@@ -0,22 +1,31 @@ | ||
/** | ||
* The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation | ||
* that is available both as a standalone program or includible in other | ||
* applications. It can be accessed using: | ||
* | ||
* ```js | ||
* const repl = require('node:repl'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) | ||
*/ | ||
declare module "repl" { | ||
import { Interface, Completer, AsyncCompleter } from "readline"; | ||
import { Context } from "vm"; | ||
import { InspectOptions } from "util"; | ||
import { AsyncCompleter, Completer, Interface } from "node:readline"; | ||
import { Context } from "node:vm"; | ||
import { InspectOptions } from "node:util"; | ||
interface ReplOptions { | ||
/** | ||
* The input prompt to display. | ||
* Default: `"> "` | ||
* @default "> " | ||
*/ | ||
prompt?: string; | ||
prompt?: string | undefined; | ||
/** | ||
* The `Readable` stream from which REPL input will be read. | ||
* Default: `process.stdin` | ||
* @default process.stdin | ||
*/ | ||
input?: NodeJS.ReadableStream; | ||
input?: NodeJS.ReadableStream | undefined; | ||
/** | ||
* The `Writable` stream to which REPL output will be written. | ||
* Default: `process.stdout` | ||
* @default process.stdout | ||
*/ | ||
output?: NodeJS.WritableStream; | ||
output?: NodeJS.WritableStream | undefined; | ||
/** | ||
@@ -28,3 +37,3 @@ * If `true`, specifies that the output should be treated as a TTY terminal, and have | ||
*/ | ||
terminal?: boolean; | ||
terminal?: boolean | undefined; | ||
/** | ||
@@ -36,6 +45,6 @@ * The function to be used when evaluating each given line of input. | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions | ||
*/ | ||
eval?: REPLEval; | ||
eval?: REPLEval | undefined; | ||
/** | ||
@@ -45,3 +54,3 @@ * Defines if the repl prints output previews or not. | ||
*/ | ||
preview?: boolean; | ||
preview?: boolean | undefined; | ||
/** | ||
@@ -53,3 +62,3 @@ * If `true`, specifies that the default `writer` function should include ANSI color | ||
*/ | ||
useColors?: boolean; | ||
useColors?: boolean | undefined; | ||
/** | ||
@@ -61,3 +70,3 @@ * If `true`, specifies that the default evaluation function will use the JavaScript | ||
*/ | ||
useGlobal?: boolean; | ||
useGlobal?: boolean | undefined; | ||
/** | ||
@@ -68,3 +77,3 @@ * If `true`, specifies that the default writer will not output the return value of a | ||
*/ | ||
ignoreUndefined?: boolean; | ||
ignoreUndefined?: boolean | undefined; | ||
/** | ||
@@ -74,11 +83,11 @@ * The function to invoke to format the output of each command before writing to `output`. | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output | ||
*/ | ||
writer?: REPLWriter; | ||
writer?: REPLWriter | undefined; | ||
/** | ||
* An optional function used for custom Tab auto completion. | ||
* | ||
* @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function | ||
*/ | ||
completer?: Completer | AsyncCompleter; | ||
completer?: Completer | AsyncCompleter | undefined; | ||
/** | ||
@@ -92,3 +101,3 @@ * A flag that specifies whether the default evaluator executes all JavaScript commands in | ||
*/ | ||
replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; | ||
replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; | ||
/** | ||
@@ -99,8 +108,12 @@ * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is | ||
*/ | ||
breakEvalOnSigint?: boolean; | ||
breakEvalOnSigint?: boolean | undefined; | ||
} | ||
type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; | ||
type REPLEval = ( | ||
this: REPLServer, | ||
evalCmd: string, | ||
context: Context, | ||
file: string, | ||
cb: (err: Error | null, result: any) => void, | ||
) => void; | ||
type REPLWriter = (this: REPLServer, obj: any) => string; | ||
/** | ||
@@ -110,6 +123,6 @@ * This is the default "writer" value, if none is passed in the REPL options, | ||
*/ | ||
const writer: REPLWriter & { options: InspectOptions }; | ||
const writer: REPLWriter & { | ||
options: InspectOptions; | ||
}; | ||
type REPLCommandAction = (this: REPLServer, text: string) => void; | ||
interface REPLCommand { | ||
@@ -119,3 +132,3 @@ /** | ||
*/ | ||
help?: string; | ||
help?: string | undefined; | ||
/** | ||
@@ -126,18 +139,15 @@ * The function to execute, optionally accepting a single string argument. | ||
} | ||
/** | ||
* Provides a customizable Read-Eval-Print-Loop (REPL). | ||
* Instances of `repl.REPLServer` are created using the {@link start} method | ||
* or directly using the JavaScript `new` keyword. | ||
* | ||
* Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those | ||
* according to a user-defined evaluation function, then output the result. Input and output | ||
* may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. | ||
* ```js | ||
* const repl = require('node:repl'); | ||
* | ||
* Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style | ||
* line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session | ||
* state, error recovery, and customizable evaluation functions. | ||
* const options = { useColors: true }; | ||
* | ||
* Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ | ||
* be created directly using the JavaScript `new` keyword. | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl | ||
* const firstInstance = repl.start(options); | ||
* const secondInstance = new repl.REPLServer(options); | ||
* ``` | ||
* @since v0.1.91 | ||
*/ | ||
@@ -173,3 +183,3 @@ class REPLServer extends Interface { | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys | ||
*/ | ||
@@ -180,3 +190,3 @@ readonly editorMode: boolean; | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
*/ | ||
@@ -187,3 +197,3 @@ readonly underscoreAssigned: boolean; | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
*/ | ||
@@ -195,3 +205,3 @@ readonly last: any; | ||
* @since v9.8.0 | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
*/ | ||
@@ -203,3 +213,3 @@ readonly underscoreErrAssigned: boolean; | ||
* @since v9.8.0 | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable | ||
*/ | ||
@@ -248,3 +258,2 @@ readonly lastError: any; | ||
readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; | ||
/** | ||
@@ -258,48 +267,75 @@ * NOTE: According to the documentation: | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver | ||
*/ | ||
private constructor(); | ||
/** | ||
* Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked | ||
* by typing a `.` followed by the `keyword`. | ||
* The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands | ||
* to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following | ||
* properties: | ||
* | ||
* The following example shows two new commands added to the REPL instance: | ||
* | ||
* ```js | ||
* const repl = require('node:repl'); | ||
* | ||
* const replServer = repl.start({ prompt: '> ' }); | ||
* replServer.defineCommand('sayhello', { | ||
* help: 'Say hello', | ||
* action(name) { | ||
* this.clearBufferedCommand(); | ||
* console.log(`Hello, ${name}!`); | ||
* this.displayPrompt(); | ||
* }, | ||
* }); | ||
* replServer.defineCommand('saybye', function saybye() { | ||
* console.log('Goodbye!'); | ||
* this.close(); | ||
* }); | ||
* ``` | ||
* | ||
* The new commands can then be used from within the REPL instance: | ||
* | ||
* ```console | ||
* > .sayhello Node.js User | ||
* Hello, Node.js User! | ||
* > .saybye | ||
* Goodbye! | ||
* ``` | ||
* @since v0.3.0 | ||
* @param keyword The command keyword (_without_ a leading `.` character). | ||
* @param cmd The function to invoke when the command is processed. | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd | ||
*/ | ||
defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; | ||
/** | ||
* 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. | ||
* 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 'prompt'. | ||
* When multi-line input is being entered, an ellipsis is printed rather than the | ||
* 'prompt'. | ||
* | ||
* This method is primarily intended to be called from within the action function for | ||
* commands registered using the `replServer.defineCommand()` method. | ||
* When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. | ||
* | ||
* @param preserveCursor When `true`, the cursor placement will not be reset to `0`. | ||
* The `replServer.displayPrompt` method is primarily intended to be called from | ||
* within the action function for commands registered using the`replServer.defineCommand()` method. | ||
* @since v0.1.91 | ||
*/ | ||
displayPrompt(preserveCursor?: boolean): void; | ||
/** | ||
* Clears any command that has been buffered but not yet executed. | ||
* | ||
* This method is primarily intended to be called from within the action function for | ||
* commands registered using the `replServer.defineCommand()` method. | ||
* | ||
* The `replServer.clearBufferedCommand()` method clears any command that has been | ||
* buffered but not yet executed. This method is primarily intended to be | ||
* called from within the action function for commands registered using the`replServer.defineCommand()` method. | ||
* @since v9.0.0 | ||
*/ | ||
clearBufferedCommand(): void; | ||
/** | ||
* Initializes a history log file for the REPL instance. When executing the | ||
* Node.js binary and using the command line REPL, a history file is initialized | ||
* Node.js binary and using the command-line REPL, a history file is initialized | ||
* by default. However, this is not the case when creating a REPL | ||
* programmatically. Use this method to initialize a history log file when working | ||
* with REPL instances programmatically. | ||
* @param path The path to the history file | ||
* @since v11.10.0 | ||
* @param historyPath the path to the history file | ||
* @param callback called when history writes are ready or upon error | ||
*/ | ||
setupHistory(path: string, cb: (err: Error | null, repl: this) => void): void; | ||
setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; | ||
/** | ||
@@ -317,3 +353,2 @@ * events.EventEmitter | ||
*/ | ||
addListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -329,3 +364,2 @@ addListener(event: "close", listener: () => void): this; | ||
addListener(event: "reset", listener: (context: Context) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -341,3 +375,2 @@ emit(event: "close"): boolean; | ||
emit(event: "reset", context: Context): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -353,3 +386,2 @@ on(event: "close", listener: () => void): this; | ||
on(event: "reset", listener: (context: Context) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -365,3 +397,2 @@ once(event: "close", listener: () => void): this; | ||
once(event: "reset", listener: (context: Context) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -377,3 +408,2 @@ prependListener(event: "close", listener: () => void): this; | ||
prependListener(event: "reset", listener: (context: Context) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -390,3 +420,2 @@ prependOnceListener(event: "close", listener: () => void): this; | ||
} | ||
/** | ||
@@ -396,3 +425,2 @@ * A flag passed in the REPL options. Evaluates expressions in sloppy mode. | ||
const REPL_MODE_SLOPPY: unique symbol; | ||
/** | ||
@@ -403,21 +431,28 @@ * A flag passed in the REPL options. Evaluates expressions in strict mode. | ||
const REPL_MODE_STRICT: unique symbol; | ||
/** | ||
* Creates and starts a `repl.REPLServer` instance. | ||
* The `repl.start()` method creates and starts a {@link REPLServer} instance. | ||
* | ||
* @param options The options for the `REPLServer`. If `options` is a string, then it specifies | ||
* the input prompt. | ||
* If `options` is a string, then it specifies the input prompt: | ||
* | ||
* ```js | ||
* const repl = require('node:repl'); | ||
* | ||
* // a Unix style prompt | ||
* repl.start('$ '); | ||
* ``` | ||
* @since v0.1.91 | ||
*/ | ||
function start(options?: string | ReplOptions): REPLServer; | ||
/** | ||
* Indicates a recoverable error that a `REPLServer` can use to support multi-line input. | ||
* | ||
* @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors | ||
* @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors | ||
*/ | ||
class Recoverable extends SyntaxError { | ||
err: Error; | ||
constructor(err: Error); | ||
} | ||
} | ||
declare module "node:repl" { | ||
export * from "repl"; | ||
} |
@@ -0,7 +1,67 @@ | ||
/** | ||
* The `node:string_decoder` module provides an API for decoding `Buffer` objects | ||
* into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 | ||
* characters. It can be accessed using: | ||
* | ||
* ```js | ||
* const { StringDecoder } = require('node:string_decoder'); | ||
* ``` | ||
* | ||
* The following example shows the basic use of the `StringDecoder` class. | ||
* | ||
* ```js | ||
* const { StringDecoder } = require('node:string_decoder'); | ||
* const decoder = new StringDecoder('utf8'); | ||
* | ||
* const cent = Buffer.from([0xC2, 0xA2]); | ||
* console.log(decoder.write(cent)); // Prints: ¢ | ||
* | ||
* const euro = Buffer.from([0xE2, 0x82, 0xAC]); | ||
* console.log(decoder.write(euro)); // Prints: € | ||
* ``` | ||
* | ||
* When a `Buffer` instance is written to the `StringDecoder` instance, an | ||
* internal buffer is used to ensure that the decoded string does not contain | ||
* any incomplete multibyte characters. These are held in the buffer until the | ||
* next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. | ||
* | ||
* In the following example, the three UTF-8 encoded bytes of the European Euro | ||
* symbol (`€`) are written over three separate operations: | ||
* | ||
* ```js | ||
* const { StringDecoder } = require('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/v20.2.0/lib/string_decoder.js) | ||
*/ | ||
declare module "string_decoder" { | ||
class StringDecoder { | ||
constructor(encoding?: BufferEncoding); | ||
/** | ||
* Returns a decoded string, ensuring that any incomplete multibyte characters at | ||
* the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the | ||
* returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. | ||
* @since v0.1.99 | ||
* @param buffer The bytes to decode. | ||
*/ | ||
write(buffer: Buffer): string; | ||
/** | ||
* Returns any remaining input stored in the internal buffer as a string. Bytes | ||
* representing incomplete UTF-8 and UTF-16 characters will be replaced with | ||
* substitution characters appropriate for the character encoding. | ||
* | ||
* If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. | ||
* After `end()` is called, the `stringDecoder` object can be reused for new input. | ||
* @since v0.9.3 | ||
* @param buffer The bytes to decode. | ||
*/ | ||
end(buffer?: Buffer): string; | ||
} | ||
} | ||
declare module "node:string_decoder" { | ||
export * from "string_decoder"; | ||
} |
@@ -0,16 +1,240 @@ | ||
/** | ||
* 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. | ||
* | ||
* 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/v20.2.0/lib/timers.js) | ||
*/ | ||
declare module "timers" { | ||
function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; | ||
namespace setTimeout { | ||
function __promisify__(ms: number): Promise<void>; | ||
function __promisify__<T>(ms: number, value: T): Promise<T>; | ||
import { Abortable } from "node:events"; | ||
import { | ||
setImmediate as setImmediatePromise, | ||
setInterval as setIntervalPromise, | ||
setTimeout as setTimeoutPromise, | ||
} from "node:timers/promises"; | ||
interface TimerOptions extends Abortable { | ||
/** | ||
* Set to `false` to indicate that the scheduled `Timeout` | ||
* should not require the Node.js event loop to remain active. | ||
* @default true | ||
*/ | ||
ref?: boolean | undefined; | ||
} | ||
function clearTimeout(timeoutId: NodeJS.Timeout): void; | ||
function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; | ||
function clearInterval(intervalId: NodeJS.Timeout): void; | ||
function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; | ||
namespace setImmediate { | ||
function __promisify__(): Promise<void>; | ||
function __promisify__<T>(value: T): Promise<T>; | ||
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. | ||
*/ | ||
class Immediate implements RefCounted { | ||
/** | ||
* 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` | ||
*/ | ||
ref(): this; | ||
/** | ||
* When called, the active `Immediate` 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 `Immediate` object's callback is | ||
* invoked. Calling `immediate.unref()` multiple times will have no effect. | ||
* @since v9.7.0 | ||
* @return 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 | ||
*/ | ||
[Symbol.dispose](): void; | ||
} | ||
/** | ||
* 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 | ||
* 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 { | ||
/** | ||
* 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 | ||
* @return 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; | ||
/** | ||
* If true, the `Timeout` object will keep the Node.js event loop active. | ||
* @since v11.0.0 | ||
*/ | ||
hasRef(): boolean; | ||
/** | ||
* 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 | ||
* time. This is useful for refreshing a timer without allocating a new | ||
* JavaScript object. | ||
* | ||
* Using this on a timer that has already called its callback will reactivate the | ||
* timer. | ||
* @since v10.2.0 | ||
* @return a reference to `timeout` | ||
*/ | ||
refresh(): this; | ||
[Symbol.toPrimitive](): number; | ||
/** | ||
* Cancels the timeout. | ||
* @since v20.5.0 | ||
*/ | ||
[Symbol.dispose](): 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. | ||
* | ||
* When multiple calls to `setImmediate()` are made, the `callback` functions are | ||
* queued for execution in the order in which they are created. The entire callback | ||
* queue is processed every event loop iteration. If an immediate timer is queued | ||
* from inside an executing callback, that timer will not be triggered until the | ||
* next event loop iteration. | ||
* | ||
* 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()`. | ||
* @since v0.9.1 | ||
* @param callback The function to call at the end of this turn of the Node.js `Event Loop` | ||
* @param args Optional arguments to pass when the `callback` is called. | ||
* @return for use with {@link clearImmediate} | ||
*/ | ||
function setImmediate<TArgs extends any[]>( | ||
callback: (...args: TArgs) => void, | ||
...args: TArgs | ||
): NodeJS.Immediate; | ||
// util.promisify no rest args compability | ||
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type | ||
function setImmediate(callback: (args: void) => void): NodeJS.Immediate; | ||
namespace setImmediate { | ||
const __promisify__: typeof setImmediatePromise; | ||
} | ||
/** | ||
* Cancels an `Immediate` object created by `setImmediate()`. | ||
* @since v0.9.1 | ||
* @param immediate An `Immediate` object as returned by {@link setImmediate}. | ||
*/ | ||
function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; | ||
function queueMicrotask(callback: () => void): void; | ||
} | ||
function clearImmediate(immediateId: NodeJS.Immediate): void; | ||
} | ||
declare module "node:timers" { | ||
export * from "timers"; | ||
} |
@@ -0,10 +1,17 @@ | ||
/** | ||
* The `node:tls` module provides an implementation of the Transport Layer Security | ||
* (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. | ||
* The module can be accessed using: | ||
* | ||
* ```js | ||
* const tls = require('node:tls'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) | ||
*/ | ||
declare module "tls" { | ||
import * as crypto from "crypto"; | ||
import * as dns from "dns"; | ||
import * as net from "net"; | ||
import { X509Certificate } from "node:crypto"; | ||
import * as net from "node:net"; | ||
import * as stream from "stream"; | ||
const CLIENT_RENEG_LIMIT: number; | ||
const CLIENT_RENEG_WINDOW: number; | ||
interface Certificate { | ||
@@ -36,23 +43,99 @@ /** | ||
} | ||
interface PeerCertificate { | ||
/** | ||
* `true` if a Certificate Authority (CA), `false` otherwise. | ||
* @since v18.13.0 | ||
*/ | ||
ca: boolean; | ||
/** | ||
* The DER encoded X.509 certificate data. | ||
*/ | ||
raw: Buffer; | ||
/** | ||
* The certificate subject. | ||
*/ | ||
subject: Certificate; | ||
/** | ||
* The certificate issuer, described in the same terms as the `subject`. | ||
*/ | ||
issuer: Certificate; | ||
subjectaltname: string; | ||
infoAccess: NodeJS.Dict<string[]>; | ||
modulus: string; | ||
exponent: string; | ||
/** | ||
* The date-time the certificate is valid from. | ||
*/ | ||
valid_from: string; | ||
/** | ||
* The date-time the certificate is valid to. | ||
*/ | ||
valid_to: string; | ||
/** | ||
* The certificate serial number, as a hex string. | ||
*/ | ||
serialNumber: string; | ||
/** | ||
* The SHA-1 digest of the DER encoded certificate. | ||
* It is returned as a `:` separated hexadecimal string. | ||
*/ | ||
fingerprint: string; | ||
/** | ||
* The SHA-256 digest of the DER encoded certificate. | ||
* It is returned as a `:` separated hexadecimal string. | ||
*/ | ||
fingerprint256: string; | ||
ext_key_usage: string[]; | ||
serialNumber: string; | ||
raw: Buffer; | ||
/** | ||
* The SHA-512 digest of the DER encoded certificate. | ||
* It is returned as a `:` separated hexadecimal string. | ||
*/ | ||
fingerprint512: string; | ||
/** | ||
* The extended key usage, a set of OIDs. | ||
*/ | ||
ext_key_usage?: string[]; | ||
/** | ||
* A string containing concatenated names for the subject, | ||
* an alternative to the `subject` names. | ||
*/ | ||
subjectaltname?: string; | ||
/** | ||
* An array describing the AuthorityInfoAccess, used with OCSP. | ||
*/ | ||
infoAccess?: NodeJS.Dict<string[]>; | ||
/** | ||
* For RSA keys: The RSA bit size. | ||
* | ||
* For EC keys: The key size in bits. | ||
*/ | ||
bits?: number; | ||
/** | ||
* The RSA exponent, as a string in hexadecimal number notation. | ||
*/ | ||
exponent?: string; | ||
/** | ||
* The RSA modulus, as a hexadecimal string. | ||
*/ | ||
modulus?: string; | ||
/** | ||
* The public key. | ||
*/ | ||
pubkey?: Buffer; | ||
/** | ||
* The ASN.1 name of the OID of the elliptic curve. | ||
* Well-known curves are identified by an OID. | ||
* While it is unusual, it is possible that the curve | ||
* is identified by its mathematical properties, | ||
* in which case it will not have an OID. | ||
*/ | ||
asn1Curve?: string; | ||
/** | ||
* The NIST name for the elliptic curve,if it has one | ||
* (not all well-known curves have been assigned names by NIST). | ||
*/ | ||
nistCurve?: string; | ||
} | ||
interface DetailedPeerCertificate extends PeerCertificate { | ||
/** | ||
* The issuer certificate object. | ||
* For self-signed certificates, this may be a circular reference. | ||
*/ | ||
issuerCertificate: DetailedPeerCertificate; | ||
} | ||
interface CipherNameAndProtocol { | ||
@@ -67,3 +150,2 @@ /** | ||
version: string; | ||
/** | ||
@@ -74,3 +156,2 @@ * IETF name for the cipher suite. | ||
} | ||
interface EphemeralKeyInfo { | ||
@@ -84,3 +165,3 @@ /** | ||
*/ | ||
name?: string; | ||
name?: string | undefined; | ||
/** | ||
@@ -91,3 +172,2 @@ * The size of parameter of an ephemeral key exchange. | ||
} | ||
interface KeyObject { | ||
@@ -101,5 +181,4 @@ /** | ||
*/ | ||
passphrase?: string; | ||
passphrase?: string | undefined; | ||
} | ||
interface PxfObject { | ||
@@ -113,5 +192,4 @@ /** | ||
*/ | ||
passphrase?: string; | ||
passphrase?: string | undefined; | ||
} | ||
interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { | ||
@@ -122,12 +200,11 @@ /** | ||
*/ | ||
isServer?: boolean; | ||
isServer?: boolean | undefined; | ||
/** | ||
* An optional net.Server instance. | ||
*/ | ||
server?: net.Server; | ||
server?: net.Server | undefined; | ||
/** | ||
* An optional Buffer instance containing a TLS session. | ||
*/ | ||
session?: Buffer; | ||
session?: Buffer | undefined; | ||
/** | ||
@@ -138,5 +215,14 @@ * If true, specifies that the OCSP status request extension will be | ||
*/ | ||
requestOCSP?: boolean; | ||
requestOCSP?: boolean | undefined; | ||
} | ||
/** | ||
* Performs transparent encryption of written data and all required TLS | ||
* negotiation. | ||
* | ||
* Instances of `tls.TLSSocket` implement the duplex `Stream` interface. | ||
* | ||
* Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the | ||
* connection is open. | ||
* @since v0.11.4 | ||
*/ | ||
class TLSSocket extends net.Socket { | ||
@@ -147,76 +233,87 @@ /** | ||
constructor(socket: net.Socket, options?: TLSSocketOptions); | ||
/** | ||
* A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. | ||
* This property is `true` if the peer certificate was signed by one of the CAs | ||
* specified when creating the `tls.TLSSocket` instance, otherwise `false`. | ||
* @since v0.11.4 | ||
*/ | ||
authorized: boolean; | ||
/** | ||
* The reason why the peer's certificate has not been verified. | ||
* This property becomes available only when tlsSocket.authorized === false. | ||
* Returns the reason why the peer's certificate was not been verified. This | ||
* property is set only when `tlsSocket.authorized === false`. | ||
* @since v0.11.4 | ||
*/ | ||
authorizationError: Error; | ||
/** | ||
* Static boolean value, always true. | ||
* May be used to distinguish TLS sockets from regular ones. | ||
* Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. | ||
* @since v0.11.4 | ||
*/ | ||
encrypted: boolean; | ||
encrypted: true; | ||
/** | ||
* String containing the selected ALPN protocol. | ||
* When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. | ||
* Before a handshake has completed, this value is always null. | ||
* When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. | ||
*/ | ||
alpnProtocol?: string; | ||
alpnProtocol: string | false | null; | ||
/** | ||
* Returns an object representing the local certificate. The returned | ||
* object has some properties corresponding to the fields of the | ||
* certificate. | ||
* Returns an object representing the local certificate. The returned object has | ||
* some properties corresponding to the fields of the certificate. | ||
* | ||
* See tls.TLSSocket.getPeerCertificate() for an example of the | ||
* certificate structure. | ||
* See {@link TLSSocket.getPeerCertificate} for an example of the certificate | ||
* structure. | ||
* | ||
* If there is no local certificate, an empty object will be returned. | ||
* If the socket has been destroyed, null will be returned. | ||
* If there is no local certificate, an empty object will be returned. If the | ||
* socket has been destroyed, `null` will be returned. | ||
* @since v11.2.0 | ||
*/ | ||
getCertificate(): PeerCertificate | object | null; | ||
/** | ||
* Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. | ||
* @returns Returns an object representing the cipher name | ||
* and the SSL/TLS protocol version of the current connection. | ||
* Returns an object containing information on the negotiated cipher suite. | ||
* | ||
* For example, a TLSv1.2 protocol with AES256-SHA cipher: | ||
* | ||
* ```json | ||
* { | ||
* "name": "AES256-SHA", | ||
* "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", | ||
* "version": "SSLv3" | ||
* } | ||
* ``` | ||
* | ||
* See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. | ||
* @since v0.11.4 | ||
*/ | ||
getCipher(): CipherNameAndProtocol; | ||
/** | ||
* Returns an object representing the type, name, and size of parameter | ||
* of an ephemeral key exchange in Perfect Forward Secrecy on a client | ||
* Returns an object representing the type, name, and size of parameter of | ||
* an ephemeral key exchange in `perfect forward secrecy` on a client | ||
* connection. It returns an empty object when the key exchange is not | ||
* ephemeral. As this is only supported on a client socket; null is | ||
* returned if called on a server socket. The supported types are 'DH' | ||
* and 'ECDH'. The name property is available only when type is 'ECDH'. | ||
* ephemeral. As this is only supported on a client socket; `null` is returned | ||
* if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. | ||
* | ||
* For example: { type: 'ECDH', name: 'prime256v1', size: 256 }. | ||
* For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. | ||
* @since v5.0.0 | ||
*/ | ||
getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; | ||
/** | ||
* Returns the latest Finished message that has | ||
* been sent to the socket as part of a SSL/TLS handshake, or undefined | ||
* if no Finished message has been sent yet. | ||
* As the `Finished` messages are message digests of the complete handshake | ||
* (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can | ||
* be used for external authentication procedures when the authentication | ||
* provided by SSL/TLS is not desired or is not enough. | ||
* | ||
* As the Finished messages are message digests of the complete | ||
* handshake (with a total of 192 bits for TLS 1.0 and more for SSL | ||
* 3.0), they can be used for external authentication procedures when | ||
* the authentication provided by SSL/TLS is not desired or is not | ||
* enough. | ||
* | ||
* Corresponds to the SSL_get_finished routine in OpenSSL and may be | ||
* used to implement the tls-unique channel binding from RFC 5929. | ||
* Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used | ||
* to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). | ||
* @since v9.9.0 | ||
* @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. | ||
*/ | ||
getFinished(): Buffer | undefined; | ||
/** | ||
* Returns an object representing the peer's certificate. | ||
* The returned object has some properties corresponding to the field of the certificate. | ||
* If detailed argument is true the full chain with issuer property will be returned, | ||
* if false only the top certificate without issuer property. | ||
* If the peer does not provide a certificate, it returns null or an empty object. | ||
* @param detailed - If true; the full chain with issuer property will be returned. | ||
* @returns An object representing the peer's certificate. | ||
* Returns an object representing the peer's certificate. If the peer does not | ||
* provide a certificate, an empty object will be returned. If the socket has been | ||
* destroyed, `null` will be returned. | ||
* | ||
* If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's | ||
* certificate. | ||
* @since v0.11.4 | ||
* @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. | ||
* @return A certificate object. | ||
*/ | ||
@@ -227,75 +324,109 @@ getPeerCertificate(detailed: true): DetailedPeerCertificate; | ||
/** | ||
* Returns the latest Finished message that is expected or has actually | ||
* been received from the socket as part of a SSL/TLS handshake, or | ||
* undefined if there is no Finished message so far. | ||
* As the `Finished` messages are message digests of the complete handshake | ||
* (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can | ||
* be used for external authentication procedures when the authentication | ||
* provided by SSL/TLS is not desired or is not enough. | ||
* | ||
* As the Finished messages are message digests of the complete | ||
* handshake (with a total of 192 bits for TLS 1.0 and more for SSL | ||
* 3.0), they can be used for external authentication procedures when | ||
* the authentication provided by SSL/TLS is not desired or is not | ||
* enough. | ||
* | ||
* Corresponds to the SSL_get_peer_finished routine in OpenSSL and may | ||
* be used to implement the tls-unique channel binding from RFC 5929. | ||
* Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used | ||
* to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). | ||
* @since v9.9.0 | ||
* @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so | ||
* far. | ||
*/ | ||
getPeerFinished(): Buffer | undefined; | ||
/** | ||
* Returns a string containing the negotiated SSL/TLS protocol version of the current connection. | ||
* The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. | ||
* The value `null` will be returned for server sockets or disconnected client sockets. | ||
* See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. | ||
* @returns negotiated SSL/TLS protocol version of the current connection | ||
* Returns a string containing the negotiated SSL/TLS protocol version of the | ||
* current connection. The value `'unknown'` will be returned for connected | ||
* sockets that have not completed the handshaking process. The value `null` will | ||
* be returned for server sockets or disconnected client sockets. | ||
* | ||
* Protocol versions are: | ||
* | ||
* * `'SSLv3'` | ||
* * `'TLSv1'` | ||
* * `'TLSv1.1'` | ||
* * `'TLSv1.2'` | ||
* * `'TLSv1.3'` | ||
* | ||
* See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. | ||
* @since v5.7.0 | ||
*/ | ||
getProtocol(): string | null; | ||
/** | ||
* Could be used to speed up handshake establishment when reconnecting to the server. | ||
* @returns ASN.1 encoded TLS session or undefined if none was negotiated. | ||
* Returns the TLS session data or `undefined` if no session was | ||
* negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful | ||
* for debugging. | ||
* | ||
* See `Session Resumption` for more information. | ||
* | ||
* Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications | ||
* must use the `'session'` event (it also works for TLSv1.2 and below). | ||
* @since v0.11.4 | ||
*/ | ||
getSession(): Buffer | undefined; | ||
/** | ||
* Returns a list of signature algorithms shared between the server and | ||
* the client in the order of decreasing preference. | ||
* See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. | ||
* @since v12.11.0 | ||
* @return List of signature algorithms shared between the server and the client in the order of decreasing preference. | ||
*/ | ||
getSharedSigalgs(): string[]; | ||
/** | ||
* NOTE: Works only with client TLS sockets. | ||
* Useful only for debugging, for session reuse provide session option to tls.connect(). | ||
* @returns TLS session ticket or undefined if none was negotiated. | ||
* For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. | ||
* | ||
* It may be useful for debugging. | ||
* | ||
* See `Session Resumption` for more information. | ||
* @since v0.11.4 | ||
*/ | ||
getTLSTicket(): Buffer | undefined; | ||
/** | ||
* Returns true if the session was reused, false otherwise. | ||
* See `Session Resumption` for more information. | ||
* @since v0.5.6 | ||
* @return `true` if the session was reused, `false` otherwise. | ||
*/ | ||
isSessionReused(): boolean; | ||
/** | ||
* Initiate TLS renegotiation process. | ||
* The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. | ||
* Upon completion, the `callback` function will be passed a single argument | ||
* that is either an `Error` (if the request failed) or `null`. | ||
* | ||
* NOTE: Can be used to request peer's certificate after the secure connection has been established. | ||
* ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. | ||
* @param options - The options may contain the following fields: rejectUnauthorized, | ||
* requestCert (See tls.createServer() for details). | ||
* @param callback - callback(err) will be executed with null as err, once the renegotiation | ||
* is successfully completed. | ||
* @return `undefined` when socket is destroy, `false` if negotiaion can't be initiated. | ||
* This method can be used to request a peer's certificate after the secure | ||
* connection has been established. | ||
* | ||
* When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. | ||
* | ||
* For TLSv1.3, renegotiation cannot be initiated, it is not supported by the | ||
* protocol. | ||
* @since v0.11.8 | ||
* @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with | ||
* an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. | ||
* @return `true` if renegotiation was initiated, `false` otherwise. | ||
*/ | ||
renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): undefined | boolean; | ||
renegotiate( | ||
options: { | ||
rejectUnauthorized?: boolean | undefined; | ||
requestCert?: boolean | undefined; | ||
}, | ||
callback: (err: Error | null) => void, | ||
): undefined | boolean; | ||
/** | ||
* Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). | ||
* Smaller fragment size decreases buffering latency on the client: large fragments are buffered by | ||
* the TLS layer until the entire fragment is received and its integrity is verified; | ||
* large fragments can span multiple roundtrips, and their processing can be delayed due to packet | ||
* loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, | ||
* which may decrease overall server throughput. | ||
* @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). | ||
* @returns Returns true on success, false otherwise. | ||
* The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. | ||
* Returns `true` if setting the limit succeeded; `false` otherwise. | ||
* | ||
* Smaller fragment sizes decrease the buffering latency on the client: larger | ||
* fragments are buffered by the TLS layer until the entire fragment is received | ||
* and its integrity is verified; large fragments can span multiple roundtrips | ||
* and their processing can be delayed due to packet loss or reordering. However, | ||
* smaller fragments add extra TLS framing bytes and CPU overhead, which may | ||
* decrease overall server throughput. | ||
* @since v0.11.11 | ||
* @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. | ||
*/ | ||
setMaxSendFragment(size: number): boolean; | ||
/** | ||
* Disables TLS renegotiation for this TLSSocket instance. Once called, | ||
* attempts to renegotiate will trigger an 'error' event on the | ||
* TLSSocket. | ||
* Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts | ||
* to renegotiate will trigger an `'error'` event on the `TLSSocket`. | ||
* @since v8.4.0 | ||
*/ | ||
disableRenegotiation(): void; | ||
/** | ||
@@ -305,17 +436,51 @@ * When enabled, TLS packet trace information is written to `stderr`. This can be | ||
* | ||
* Note: The format of the output is identical to the output of `openssl s_client | ||
* -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's | ||
* `SSL_trace()` function, the format is undocumented, can change without notice, | ||
* and should not be relied on. | ||
* The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by | ||
* OpenSSL's `SSL_trace()` function, the format is undocumented, can change | ||
* without notice, and should not be relied on. | ||
* @since v12.2.0 | ||
*/ | ||
enableTrace(): void; | ||
/** | ||
* Returns the peer certificate as an `X509Certificate` object. | ||
* | ||
* If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. | ||
* @since v15.9.0 | ||
*/ | ||
getPeerX509Certificate(): X509Certificate | undefined; | ||
/** | ||
* Returns the local certificate as an `X509Certificate` object. | ||
* | ||
* If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. | ||
* @since v15.9.0 | ||
*/ | ||
getX509Certificate(): X509Certificate | undefined; | ||
/** | ||
* Keying material is used for validations to prevent different kind of attacks in | ||
* network protocols, for example in the specifications of IEEE 802.1X. | ||
* | ||
* Example | ||
* | ||
* ```js | ||
* const keyingMaterial = tlsSocket.exportKeyingMaterial( | ||
* 128, | ||
* 'client finished'); | ||
* | ||
* /* | ||
* Example return value of keyingMaterial: | ||
* <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9 | ||
* 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91 | ||
* 74 ef 2c ... 78 more bytes> | ||
* | ||
* ``` | ||
* | ||
* See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more | ||
* information. | ||
* @since v13.10.0, v12.17.0 | ||
* @param length number of bytes to retrieve from keying material | ||
* @param label an application specific label, typically this will be a value from the | ||
* [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). | ||
* @param context optionally provide a context. | ||
* @param label an application specific label, typically this will be a value from the [IANA Exporter Label | ||
* Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). | ||
* @param context Optionally provide a context. | ||
* @return requested bytes of the keying material | ||
*/ | ||
exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; | ||
addListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -326,3 +491,2 @@ addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; | ||
addListener(event: "keylog", listener: (line: Buffer) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
@@ -333,3 +497,2 @@ emit(event: "OCSPResponse", response: Buffer): boolean; | ||
emit(event: "keylog", line: Buffer): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
@@ -340,3 +503,2 @@ on(event: "OCSPResponse", listener: (response: Buffer) => void): this; | ||
on(event: "keylog", listener: (line: Buffer) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
@@ -347,3 +509,2 @@ once(event: "OCSPResponse", listener: (response: Buffer) => void): this; | ||
once(event: "keylog", listener: (line: Buffer) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -354,3 +515,2 @@ prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; | ||
prependListener(event: "keylog", listener: (line: Buffer) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
@@ -362,3 +522,2 @@ prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; | ||
} | ||
interface CommonConnectionOptions { | ||
@@ -368,4 +527,3 @@ /** | ||
*/ | ||
secureContext?: SecureContext; | ||
secureContext?: SecureContext | undefined; | ||
/** | ||
@@ -376,3 +534,3 @@ * When enabled, TLS packet trace information is written to `stderr`. This can be | ||
*/ | ||
enableTrace?: boolean; | ||
enableTrace?: boolean | undefined; | ||
/** | ||
@@ -383,3 +541,3 @@ * If true the server will request a certificate from clients that | ||
*/ | ||
requestCert?: boolean; | ||
requestCert?: boolean | undefined; | ||
/** | ||
@@ -389,3 +547,3 @@ * An array of strings or a Buffer naming possible ALPN protocols. | ||
*/ | ||
ALPNProtocols?: string[] | Uint8Array[] | Uint8Array; | ||
ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; | ||
/** | ||
@@ -400,3 +558,3 @@ * SNICallback(servername, cb) <Function> A function that will be | ||
*/ | ||
SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; | ||
SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; | ||
/** | ||
@@ -408,6 +566,5 @@ * If true the server will reject any connection which is not | ||
*/ | ||
rejectUnauthorized?: boolean; | ||
rejectUnauthorized?: boolean | undefined; | ||
} | ||
interface TlsOptions extends SecureContextOptions, CommonConnectionOptions { | ||
interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { | ||
/** | ||
@@ -419,3 +576,3 @@ * Abort the connection if the SSL/TLS handshake does not finish in the | ||
*/ | ||
handshakeTimeout?: number; | ||
handshakeTimeout?: number | undefined; | ||
/** | ||
@@ -426,10 +583,8 @@ * The number of seconds after which a TLS session created by the | ||
*/ | ||
sessionTimeout?: number; | ||
sessionTimeout?: number | undefined; | ||
/** | ||
* 48-bytes of cryptographically strong pseudo-random data. | ||
*/ | ||
ticketKeys?: Buffer; | ||
ticketKeys?: Buffer | undefined; | ||
/** | ||
* | ||
* @param socket | ||
@@ -452,3 +607,2 @@ * @param identity identity parameter sent from the client. | ||
*/ | ||
pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; | ||
@@ -461,5 +615,4 @@ /** | ||
*/ | ||
pskIdentityHint?: string; | ||
pskIdentityHint?: string | undefined; | ||
} | ||
interface PSKCallbackNegotation { | ||
@@ -469,14 +622,13 @@ psk: DataView | NodeJS.TypedArray; | ||
} | ||
interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { | ||
host?: string; | ||
port?: number; | ||
path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. | ||
socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket | ||
checkServerIdentity?: typeof checkServerIdentity; | ||
servername?: string; // SNI TLS Extension | ||
session?: Buffer; | ||
minDHSize?: number; | ||
lookup?: net.LookupFunction; | ||
timeout?: number; | ||
host?: string | undefined; | ||
port?: number | undefined; | ||
path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. | ||
socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket | ||
checkServerIdentity?: typeof checkServerIdentity | undefined; | ||
servername?: string | undefined; // SNI TLS Extension | ||
session?: Buffer | undefined; | ||
minDHSize?: number | undefined; | ||
lookup?: net.LookupFunction | undefined; | ||
timeout?: number | undefined; | ||
/** | ||
@@ -501,28 +653,47 @@ * When negotiating TLS-PSK (pre-shared keys), this function is called | ||
} | ||
/** | ||
* Accepts encrypted connections using TLS or SSL. | ||
* @since v0.3.2 | ||
*/ | ||
class Server extends net.Server { | ||
constructor(secureConnectionListener?: (socket: TLSSocket) => void); | ||
constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); | ||
/** | ||
* The server.addContext() method adds a secure context that will be | ||
* used if the client request's SNI name matches the supplied hostname | ||
* (or wildcard). | ||
* The `server.addContext()` method adds a secure context that will be used if | ||
* the client request's SNI name matches the supplied `hostname` (or wildcard). | ||
* | ||
* When there are multiple matching contexts, the most recently added one is | ||
* used. | ||
* @since v0.5.3 | ||
* @param hostname A SNI host name or wildcard (e.g. `'*'`) | ||
* @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, credentials: SecureContextOptions): void; | ||
addContext(hostname: string, context: SecureContextOptions): void; | ||
/** | ||
* Returns the session ticket keys. | ||
* | ||
* See `Session Resumption` for more information. | ||
* @since v3.0.0 | ||
* @return A 48-byte buffer containing the session ticket keys. | ||
*/ | ||
getTicketKeys(): Buffer; | ||
/** | ||
* | ||
* The server.setSecureContext() method replaces the | ||
* secure context of an existing server. Existing connections to the | ||
* server are not interrupted. | ||
* The `server.setSecureContext()` method replaces the secure context of an | ||
* existing server. Existing connections to the server are not interrupted. | ||
* @since v11.0.0 | ||
* @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). | ||
*/ | ||
setSecureContext(details: SecureContextOptions): void; | ||
setSecureContext(options: SecureContextOptions): void; | ||
/** | ||
* The server.setSecureContext() method replaces the secure context of | ||
* an existing server. Existing connections to the server are not | ||
* interrupted. | ||
* Sets the session ticket keys. | ||
* | ||
* Changes to the ticket keys are effective only for future server connections. | ||
* Existing or currently pending server connections will use the previous keys. | ||
* | ||
* See `Session Resumption` for more information. | ||
* @since v3.0.0 | ||
* @param keys A 48-byte buffer containing the session ticket keys. | ||
*/ | ||
setTicketKeys(keys: Buffer): void; | ||
/** | ||
@@ -539,49 +710,117 @@ * events.EventEmitter | ||
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; | ||
addListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; | ||
addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; | ||
addListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; | ||
addListener( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, | ||
): this; | ||
addListener( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
addListener( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, | ||
): this; | ||
addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; | ||
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; | ||
emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; | ||
emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; | ||
emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; | ||
emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; | ||
emit( | ||
event: "OCSPRequest", | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
): boolean; | ||
emit( | ||
event: "resumeSession", | ||
sessionId: Buffer, | ||
callback: (err: Error | null, sessionData: Buffer | null) => void, | ||
): boolean; | ||
emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; | ||
emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; | ||
on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; | ||
on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; | ||
on(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; | ||
on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; | ||
on( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
on( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, | ||
): this; | ||
on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; | ||
on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; | ||
once(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; | ||
once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; | ||
once(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; | ||
once( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, | ||
): this; | ||
once( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
once( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, | ||
): this; | ||
once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; | ||
once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; | ||
prependListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; | ||
prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; | ||
prependListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; | ||
prependListener( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, | ||
): this; | ||
prependListener( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
prependListener( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, | ||
): this; | ||
prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; | ||
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; | ||
prependOnceListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; | ||
prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; | ||
prependOnceListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; | ||
prependOnceListener( | ||
event: "newSession", | ||
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, | ||
): this; | ||
prependOnceListener( | ||
event: "OCSPRequest", | ||
listener: ( | ||
certificate: Buffer, | ||
issuer: Buffer, | ||
callback: (err: Error | null, resp: Buffer) => void, | ||
) => void, | ||
): this; | ||
prependOnceListener( | ||
event: "resumeSession", | ||
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, | ||
): this; | ||
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 { | ||
@@ -591,7 +830,16 @@ encrypted: TLSSocket; | ||
} | ||
type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; | ||
type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; | ||
interface SecureContextOptions { | ||
/** | ||
* If set, this will be called when a client opens a connection using the ALPN extension. | ||
* One argument will be passed to the callback: an object containing `servername` and `protocols` fields, | ||
* respectively containing the server name from the SNI extension (if any) and an array of | ||
* ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, | ||
* which will be returned to the client as the selected ALPN protocol, or `undefined`, | ||
* to reject the connection with a fatal alert. If a string is returned that does not match one of | ||
* the client's ALPN protocols, an error will be thrown. | ||
* 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; | ||
/** | ||
* Optionally override the trusted CA certificates. Default is to trust | ||
@@ -601,3 +849,3 @@ * the well-known CAs curated by Mozilla. Mozilla's CAs are completely | ||
*/ | ||
ca?: string | Buffer | Array<string | Buffer>; | ||
ca?: string | Buffer | Array<string | Buffer> | undefined; | ||
/** | ||
@@ -614,3 +862,3 @@ * Cert chains in PEM format. One cert chain should be provided per | ||
*/ | ||
cert?: string | Buffer | Array<string | Buffer>; | ||
cert?: string | Buffer | Array<string | Buffer> | undefined; | ||
/** | ||
@@ -622,3 +870,3 @@ * Colon-separated list of supported signature algorithms. The list | ||
*/ | ||
sigalgs?: string; | ||
sigalgs?: string | undefined; | ||
/** | ||
@@ -630,20 +878,17 @@ * Cipher suite specification, replacing the default. For more | ||
*/ | ||
ciphers?: string; | ||
ciphers?: string | undefined; | ||
/** | ||
* Name of an OpenSSL engine which can provide the client certificate. | ||
*/ | ||
clientCertEngine?: string; | ||
clientCertEngine?: string | undefined; | ||
/** | ||
* PEM formatted CRLs (Certificate Revocation Lists). | ||
*/ | ||
crl?: string | Buffer | Array<string | Buffer>; | ||
crl?: string | Buffer | Array<string | Buffer> | undefined; | ||
/** | ||
* Diffie Hellman parameters, required for Perfect Forward Secrecy. Use | ||
* openssl dhparam to create the parameters. The key length must be | ||
* greater than or equal to 1024 bits or else an error will be thrown. | ||
* Although 1024 bits is permissible, use 2048 bits or larger for | ||
* stronger security. If omitted or invalid, the parameters are | ||
* silently discarded and DHE ciphers will not be available. | ||
* `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. | ||
* If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. | ||
* ECDHE-based perfect forward secrecy will still be available. | ||
*/ | ||
dhparam?: string | Buffer; | ||
dhparam?: string | Buffer | undefined; | ||
/** | ||
@@ -658,3 +903,3 @@ * A string describing a named curve or a colon separated list of curve | ||
*/ | ||
ecdhCurve?: string; | ||
ecdhCurve?: string | undefined; | ||
/** | ||
@@ -665,3 +910,3 @@ * Attempt to use the server's cipher suite preferences instead of the | ||
*/ | ||
honorCipherOrder?: boolean; | ||
honorCipherOrder?: boolean | undefined; | ||
/** | ||
@@ -677,3 +922,3 @@ * Private keys in PEM format. PEM allows the option of private keys | ||
*/ | ||
key?: string | Buffer | Array<Buffer | KeyObject>; | ||
key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined; | ||
/** | ||
@@ -683,3 +928,3 @@ * Name of an OpenSSL engine to get private key from. Should be used | ||
*/ | ||
privateKeyEngine?: string; | ||
privateKeyEngine?: string | undefined; | ||
/** | ||
@@ -690,3 +935,3 @@ * Identifier of a private key managed by an OpenSSL engine. Should be | ||
*/ | ||
privateKeyIdentifier?: string; | ||
privateKeyIdentifier?: string | undefined; | ||
/** | ||
@@ -700,3 +945,3 @@ * Optionally set the maximum TLS version to allow. One | ||
*/ | ||
maxVersion?: SecureVersion; | ||
maxVersion?: SecureVersion | undefined; | ||
/** | ||
@@ -712,7 +957,7 @@ * Optionally set the minimum TLS version to allow. One | ||
*/ | ||
minVersion?: SecureVersion; | ||
minVersion?: SecureVersion | undefined; | ||
/** | ||
* Shared passphrase used for a single private key and/or a PFX. | ||
*/ | ||
passphrase?: string; | ||
passphrase?: string | undefined; | ||
/** | ||
@@ -728,3 +973,3 @@ * PFX or PKCS12 encoded private key and certificate chain. pfx is an | ||
*/ | ||
pfx?: string | Buffer | Array<string | Buffer | PxfObject>; | ||
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined; | ||
/** | ||
@@ -735,3 +980,3 @@ * Optionally affect the OpenSSL protocol behavior, which is not | ||
*/ | ||
secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options | ||
secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options | ||
/** | ||
@@ -748,3 +993,3 @@ * Legacy mechanism to select the TLS protocol version to use, it does | ||
*/ | ||
secureProtocol?: string; | ||
secureProtocol?: string | undefined; | ||
/** | ||
@@ -754,3 +999,3 @@ * Opaque identifier used by servers to ensure session state is not | ||
*/ | ||
sessionIdContext?: string; | ||
sessionIdContext?: string | undefined; | ||
/** | ||
@@ -760,3 +1005,3 @@ * 48-bytes of cryptographically strong pseudo-random data. | ||
*/ | ||
ticketKeys?: Buffer; | ||
ticketKeys?: Buffer | undefined; | ||
/** | ||
@@ -767,29 +1012,206 @@ * The number of seconds after which a TLS session created by the | ||
*/ | ||
sessionTimeout?: number; | ||
sessionTimeout?: number | undefined; | ||
} | ||
interface SecureContext { | ||
context: any; | ||
} | ||
/* | ||
* Verifies the certificate `cert` is issued to host `host`. | ||
* @host The hostname to verify the certificate against | ||
* @cert PeerCertificate representing the peer's certificate | ||
/** | ||
* Verifies the certificate `cert` is issued to `hostname`. | ||
* | ||
* Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. | ||
* Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on | ||
* failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). | ||
* | ||
* This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as | ||
* such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. | ||
* | ||
* This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The | ||
* overwriting function can call `tls.checkServerIdentity()` of course, to augment | ||
* the checks done with additional verification. | ||
* | ||
* This function is only called if the certificate passed all other checks, such as | ||
* being issued by trusted CA (`options.ca`). | ||
* | ||
* Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name | ||
* was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use | ||
* a custom`options.checkServerIdentity` function that implements the desired behavior. | ||
* @since v0.8.4 | ||
* @param hostname The host name or IP address to verify the certificate against. | ||
* @param cert A `certificate object` representing the peer's certificate. | ||
*/ | ||
function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; | ||
function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; | ||
/** | ||
* Creates a new {@link Server}. The `secureConnectionListener`, if provided, is | ||
* automatically set as a listener for the `'secureConnection'` event. | ||
* | ||
* The `ticketKeys` options is automatically shared between `node:cluster` module | ||
* workers. | ||
* | ||
* The following illustrates a simple echo server: | ||
* | ||
* ```js | ||
* const tls = require('node:tls'); | ||
* const fs = require('node:fs'); | ||
* | ||
* const options = { | ||
* key: fs.readFileSync('server-key.pem'), | ||
* cert: fs.readFileSync('server-cert.pem'), | ||
* | ||
* // This is necessary only if using client certificate authentication. | ||
* requestCert: true, | ||
* | ||
* // This is necessary only if the client uses a self-signed certificate. | ||
* ca: [ fs.readFileSync('client-cert.pem') ], | ||
* }; | ||
* | ||
* const server = tls.createServer(options, (socket) => { | ||
* console.log('server connected', | ||
* socket.authorized ? 'authorized' : 'unauthorized'); | ||
* socket.write('welcome!\n'); | ||
* socket.setEncoding('utf8'); | ||
* socket.pipe(socket); | ||
* }); | ||
* server.listen(8000, () => { | ||
* console.log('server bound'); | ||
* }); | ||
* ``` | ||
* | ||
* The server can be tested by connecting to it using the example client from {@link connect}. | ||
* @since v0.3.2 | ||
*/ | ||
function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; | ||
function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; | ||
/** | ||
* The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. | ||
* | ||
* `tls.connect()` returns a {@link TLSSocket} object. | ||
* | ||
* Unlike the `https` API, `tls.connect()` does not enable the | ||
* SNI (Server Name Indication) extension by default, which may cause some | ||
* servers to return an incorrect certificate or reject the connection | ||
* altogether. To enable SNI, set the `servername` option in addition | ||
* to `host`. | ||
* | ||
* The following illustrates a client for the echo server example from {@link createServer}: | ||
* | ||
* ```js | ||
* // Assumes an echo server that is listening on port 8000. | ||
* const tls = require('node:tls'); | ||
* const fs = require('node:fs'); | ||
* | ||
* const options = { | ||
* // Necessary only if the server requires client certificate authentication. | ||
* key: fs.readFileSync('client-key.pem'), | ||
* cert: fs.readFileSync('client-cert.pem'), | ||
* | ||
* // Necessary only if the server uses a self-signed certificate. | ||
* ca: [ fs.readFileSync('server-cert.pem') ], | ||
* | ||
* // Necessary only if the server's cert isn't for "localhost". | ||
* checkServerIdentity: () => { return null; }, | ||
* }; | ||
* | ||
* const socket = tls.connect(8000, options, () => { | ||
* console.log('client connected', | ||
* socket.authorized ? 'authorized' : 'unauthorized'); | ||
* process.stdin.pipe(socket); | ||
* process.stdin.resume(); | ||
* }); | ||
* socket.setEncoding('utf8'); | ||
* socket.on('data', (data) => { | ||
* console.log(data); | ||
* }); | ||
* socket.on('end', () => { | ||
* console.log('server ends connection'); | ||
* }); | ||
* ``` | ||
* @since v0.11.3 | ||
*/ | ||
function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; | ||
function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; | ||
function connect( | ||
port: number, | ||
host?: string, | ||
options?: ConnectionOptions, | ||
secureConnectListener?: () => void, | ||
): TLSSocket; | ||
function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; | ||
/** | ||
* @deprecated since v0.11.3 Use `tls.TLSSocket` instead. | ||
* 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(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; | ||
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. | ||
* | ||
* {@link createServer} uses a 128 bit truncated SHA1 hash value generated | ||
* from `process.argv` as the default value of the `sessionIdContext` option, other | ||
* APIs that create secure contexts have no default value. | ||
* | ||
* The `tls.createSecureContext()` method creates a `SecureContext` object. It is | ||
* usable as an argument to several `tls` APIs, such as `server.addContext()`, | ||
* but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. | ||
* | ||
* A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. | ||
* | ||
* If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of | ||
* CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). | ||
* | ||
* Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength | ||
* will be selected automatically. Otherwise, if necessary, `openssl dhparam` can | ||
* be used to create custom parameters. The key length must be greater than or | ||
* equal to 1024 bits or else an error will be thrown. Although 1024 bits is | ||
* permissible, use 2048 bits or larger for stronger security. | ||
* @since v0.11.13 | ||
*/ | ||
function createSecureContext(options?: SecureContextOptions): SecureContext; | ||
/** | ||
* 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`. | ||
* | ||
* Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for | ||
* TLSv1.2 and below. | ||
* | ||
* ```js | ||
* console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] | ||
* ``` | ||
* @since v0.10.2 | ||
*/ | ||
function getCiphers(): string[]; | ||
/** | ||
@@ -821,4 +1243,10 @@ * The default curve name to use for ECDH key agreement in a tls server. | ||
let DEFAULT_MIN_VERSION: SecureVersion; | ||
/** | ||
* The default value of the ciphers option of tls.createSecureContext(). | ||
* It can be assigned any of the supported OpenSSL ciphers. | ||
* Defaults to the content of crypto.constants.defaultCoreCipherList, unless | ||
* changed using CLI options using --tls-default-ciphers. | ||
*/ | ||
let DEFAULT_CIPHERS: string; | ||
/** | ||
* An immutable array of strings representing the root certificates (in PEM | ||
@@ -828,3 +1256,6 @@ * format) used for verifying peer certificates. This is the default value | ||
*/ | ||
const rootCertificates: ReadonlyArray<string>; | ||
const rootCertificates: readonly string[]; | ||
} | ||
declare module "node:tls" { | ||
export * from "tls"; | ||
} |
@@ -0,1 +1,99 @@ | ||
/** | ||
* The `node:trace_events` module provides a mechanism to centralize tracing | ||
* information generated by V8, Node.js core, and userspace code. | ||
* | ||
* Tracing can be enabled with the `--trace-event-categories` command-line flag | ||
* or by using the `node:trace_events` module. The `--trace-event-categories` flag | ||
* accepts a list of comma-separated category names. | ||
* | ||
* The available categories are: | ||
* | ||
* * `node`: An empty placeholder. | ||
* * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. | ||
* The `async_hooks` 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`. | ||
* * `node.threadpoolwork.async`: Enables capture of trace data for threadpool | ||
* asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. | ||
* * `node.dns.native`: Enables capture of trace data for DNS queries. | ||
* * `node.net.native`: Enables capture of trace data for network. | ||
* * `node.environment`: Enables capture of Node.js Environment milestones. | ||
* * `node.fs.sync`: Enables capture of trace data for file system sync methods. | ||
* * `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` 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 | ||
* measurements. | ||
* * `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` 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. | ||
* | ||
* ```bash | ||
* node --trace-event-categories v8,node,node.async_hooks server.js | ||
* ``` | ||
* | ||
* Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be | ||
* used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. | ||
* | ||
* ```bash | ||
* node --trace-events-enabled | ||
* | ||
* # is equivalent to | ||
* | ||
* node --trace-event-categories v8,node,node.async_hooks | ||
* ``` | ||
* | ||
* Alternatively, trace events may be enabled using the `node:trace_events` module: | ||
* | ||
* ```js | ||
* const trace_events = require('node:trace_events'); | ||
* const tracing = trace_events.createTracing({ categories: ['node.perf'] }); | ||
* tracing.enable(); // Enable trace event capture for the 'node.perf' category | ||
* | ||
* // do work | ||
* | ||
* tracing.disable(); // Disable trace event capture for the 'node.perf' category | ||
* ``` | ||
* | ||
* Running Node.js with tracing enabled will produce log files that can be opened | ||
* in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. | ||
* | ||
* The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can | ||
* be specified with `--trace-event-file-pattern` that accepts a template | ||
* string that supports `${rotation}` and `${pid}`: | ||
* | ||
* ```bash | ||
* node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js | ||
* ``` | ||
* | ||
* To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers | ||
* in your code, such as: | ||
* | ||
* ```js | ||
* process.on('SIGINT', function onSigint() { | ||
* console.info('Received SIGINT.'); | ||
* process.exit(130); // Or applicable exit code depending on OS and signal | ||
* }); | ||
* ``` | ||
* | ||
* The tracing system uses the same time source | ||
* as the one used by `process.hrtime()`. | ||
* 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` threads. | ||
* @experimental | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) | ||
*/ | ||
declare module "trace_events" { | ||
@@ -18,3 +116,2 @@ /** | ||
readonly categories: string; | ||
/** | ||
@@ -28,3 +125,2 @@ * Disables this `Tracing` object. | ||
disable(): void; | ||
/** | ||
@@ -35,3 +131,2 @@ * Enables this `Tracing` object for the set of categories covered by | ||
enable(): void; | ||
/** | ||
@@ -42,3 +137,2 @@ * `true` only if the `Tracing` object has been enabled. | ||
} | ||
interface CreateTracingOptions { | ||
@@ -52,15 +146,42 @@ /** | ||
} | ||
/** | ||
* Creates and returns a Tracing object for the given set of categories. | ||
* Creates and returns a `Tracing` object for the given set of `categories`. | ||
* | ||
* ```js | ||
* const trace_events = require('node:trace_events'); | ||
* const categories = ['node.perf', 'node.async_hooks']; | ||
* const tracing = trace_events.createTracing({ categories }); | ||
* tracing.enable(); | ||
* // do stuff | ||
* tracing.disable(); | ||
* ``` | ||
* @since v10.0.0 | ||
* @return . | ||
*/ | ||
function createTracing(options: CreateTracingOptions): Tracing; | ||
/** | ||
* Returns a comma-separated list of all currently-enabled trace event | ||
* categories. The current set of enabled trace event categories is | ||
* determined by the union of all currently-enabled `Tracing` objects and | ||
* any categories enabled using the `--trace-event-categories` flag. | ||
* categories. The current set of enabled trace event categories is determined | ||
* by the _union_ of all currently-enabled `Tracing` objects and any categories | ||
* enabled using the `--trace-event-categories` flag. | ||
* | ||
* 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'); | ||
* const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); | ||
* const t2 = trace_events.createTracing({ categories: ['node.perf'] }); | ||
* const t3 = trace_events.createTracing({ categories: ['v8'] }); | ||
* | ||
* t1.enable(); | ||
* t2.enable(); | ||
* | ||
* console.log(trace_events.getEnabledCategories()); | ||
* ``` | ||
* @since v10.0.0 | ||
*/ | ||
function getEnabledCategories(): string | undefined; | ||
} | ||
declare module "node:trace_events" { | ||
export * from "trace_events"; | ||
} |
@@ -0,9 +1,70 @@ | ||
/** | ||
* The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`classes. In most cases, it will not be necessary or possible to use this module | ||
* directly. However, it can be accessed using: | ||
* | ||
* ```js | ||
* const tty = require('node:tty'); | ||
* ``` | ||
* | ||
* When Node.js detects that it is being run with a text terminal ("TTY") | ||
* attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by | ||
* default, be instances of `tty.WriteStream`. The preferred method of determining | ||
* whether Node.js is being run within a TTY context is to check that the value of | ||
* the `process.stdout.isTTY` property is `true`: | ||
* | ||
* ```console | ||
* $ node -p -e "Boolean(process.stdout.isTTY)" | ||
* true | ||
* $ node -p -e "Boolean(process.stdout.isTTY)" | cat | ||
* false | ||
* ``` | ||
* | ||
* 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/v20.2.0/lib/tty.js) | ||
*/ | ||
declare module "tty" { | ||
import * as net from "net"; | ||
import * as net from "node:net"; | ||
/** | ||
* The `tty.isatty()` method returns `true` if the given `fd` is associated with | ||
* a TTY and `false` if it is not, including whenever `fd` is not a non-negative | ||
* integer. | ||
* @since v0.5.8 | ||
* @param fd A numeric file descriptor | ||
*/ | ||
function isatty(fd: number): boolean; | ||
/** | ||
* Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js | ||
* process and there should be no reason to create additional instances. | ||
* @since v0.5.8 | ||
*/ | ||
class ReadStream extends net.Socket { | ||
constructor(fd: number, options?: net.SocketConstructorOpts); | ||
/** | ||
* A `boolean` that is `true` if the TTY is currently configured to operate as a | ||
* raw device. | ||
* | ||
* This flag is always `false` when a process starts, even if the terminal is | ||
* operating in raw mode. Its value will change with subsequent calls to`setRawMode`. | ||
* @since v0.7.7 | ||
*/ | ||
isRaw: boolean; | ||
/** | ||
* Allows configuration of `tty.ReadStream` so that it operates as a raw device. | ||
* | ||
* When in raw mode, input is always available character-by-character, not | ||
* including modifiers. Additionally, all special processing of characters by the | ||
* terminal is disabled, including echoing input | ||
* characters. Ctrl+C will no longer cause a `SIGINT` when | ||
* in this mode. | ||
* @since v0.7.7 | ||
* @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` | ||
* property will be set to the resulting mode. | ||
* @return The read stream instance. | ||
*/ | ||
setRawMode(mode: boolean): this; | ||
/** | ||
* A `boolean` that is always `true` for `tty.ReadStream` instances. | ||
* @since v0.5.8 | ||
*/ | ||
isTTY: boolean; | ||
@@ -17,2 +78,7 @@ } | ||
type Direction = -1 | 0 | 1; | ||
/** | ||
* Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there | ||
* should be no reason to create additional instances. | ||
* @since v0.5.8 | ||
*/ | ||
class WriteStream extends net.Socket { | ||
@@ -22,28 +88,34 @@ constructor(fd: number); | ||
addListener(event: "resize", listener: () => void): this; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
emit(event: "resize"): boolean; | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
on(event: "resize", listener: () => void): this; | ||
once(event: string, listener: (...args: any[]) => void): this; | ||
once(event: "resize", listener: () => void): this; | ||
prependListener(event: string, listener: (...args: any[]) => void): this; | ||
prependListener(event: "resize", listener: () => void): this; | ||
prependOnceListener(event: string, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: "resize", listener: () => void): this; | ||
/** | ||
* Clears the current line of this WriteStream in a direction identified by `dir`. | ||
* `writeStream.clearLine()` clears the current line of this `WriteStream` in a | ||
* direction identified by `dir`. | ||
* @since v0.7.7 | ||
* @param callback Invoked once the operation completes. | ||
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. | ||
*/ | ||
clearLine(dir: Direction, callback?: () => void): boolean; | ||
/** | ||
* Clears this `WriteStream` from the current cursor down. | ||
* `writeStream.clearScreenDown()` clears this `WriteStream` from the current | ||
* cursor down. | ||
* @since v0.7.7 | ||
* @param callback Invoked once the operation completes. | ||
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. | ||
*/ | ||
clearScreenDown(callback?: () => void): boolean; | ||
/** | ||
* Moves this WriteStream's cursor to the specified position. | ||
* `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified | ||
* position. | ||
* @since v0.7.7 | ||
* @param callback Invoked once the operation completes. | ||
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. | ||
*/ | ||
@@ -53,17 +125,87 @@ cursorTo(x: number, y?: number, callback?: () => void): boolean; | ||
/** | ||
* Moves this WriteStream's cursor relative to its current position. | ||
* `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its | ||
* current position. | ||
* @since v0.7.7 | ||
* @param callback Invoked once the operation completes. | ||
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. | ||
*/ | ||
moveCursor(dx: number, dy: number, callback?: () => void): boolean; | ||
/** | ||
* @default `process.env` | ||
* Returns: | ||
* | ||
* * `1` for 2, | ||
* * `4` for 16, | ||
* * `8` for 256, | ||
* * `24` for 16,777,216 colors supported. | ||
* | ||
* Use this to determine what colors the terminal supports. Due to the nature of | ||
* colors in terminals it is possible to either have false positives or false | ||
* negatives. It depends on process information and the environment variables that | ||
* may lie about what terminal is used. | ||
* It is possible to pass in an `env` object to simulate the usage of a specific | ||
* terminal. This can be useful to check how specific environment settings behave. | ||
* | ||
* To enforce a specific color support, use one of the below environment settings. | ||
* | ||
* * 2 colors: `FORCE_COLOR = 0` (Disables colors) | ||
* * 16 colors: `FORCE_COLOR = 1` | ||
* * 256 colors: `FORCE_COLOR = 2` | ||
* * 16,777,216 colors: `FORCE_COLOR = 3` | ||
* | ||
* Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. | ||
* @since v9.9.0 | ||
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. | ||
*/ | ||
getColorDepth(env?: {}): number; | ||
hasColors(depth?: number): boolean; | ||
hasColors(env?: {}): boolean; | ||
hasColors(depth: number, env?: {}): boolean; | ||
getColorDepth(env?: object): number; | ||
/** | ||
* Returns `true` if the `writeStream` supports at least as many colors as provided | ||
* in `count`. Minimum support is 2 (black and white). | ||
* | ||
* This has the same false positives and negatives as described in `writeStream.getColorDepth()`. | ||
* | ||
* ```js | ||
* process.stdout.hasColors(); | ||
* // Returns true or false depending on if `stdout` supports at least 16 colors. | ||
* process.stdout.hasColors(256); | ||
* // Returns true or false depending on if `stdout` supports at least 256 colors. | ||
* process.stdout.hasColors({ TMUX: '1' }); | ||
* // Returns true. | ||
* process.stdout.hasColors(2 ** 24, { TMUX: '1' }); | ||
* // Returns false (the environment setting pretends to support 2 ** 8 colors). | ||
* ``` | ||
* @since v11.13.0, v10.16.0 | ||
* @param [count=16] The number of colors that are requested (minimum 2). | ||
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. | ||
*/ | ||
hasColors(count?: number): boolean; | ||
hasColors(env?: object): boolean; | ||
hasColors(count: number, env?: object): boolean; | ||
/** | ||
* `writeStream.getWindowSize()` returns the size of the TTY | ||
* corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number | ||
* of columns and rows in the corresponding TTY. | ||
* @since v0.7.7 | ||
*/ | ||
getWindowSize(): [number, number]; | ||
/** | ||
* A `number` specifying the number of columns the TTY currently has. This property | ||
* is updated whenever the `'resize'` event is emitted. | ||
* @since v0.7.7 | ||
*/ | ||
columns: number; | ||
/** | ||
* A `number` specifying the number of rows the TTY currently has. This property | ||
* is updated whenever the `'resize'` event is emitted. | ||
* @since v0.7.7 | ||
*/ | ||
rows: number; | ||
/** | ||
* A `boolean` that is always `true`. | ||
* @since v0.5.8 | ||
*/ | ||
isTTY: boolean; | ||
} | ||
} | ||
declare module "node:tty" { | ||
export * from "tty"; | ||
} |
@@ -0,19 +1,28 @@ | ||
/** | ||
* The `node:url` module provides utilities for URL resolution and parsing. It can | ||
* be accessed using: | ||
* | ||
* ```js | ||
* import url from 'node:url'; | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/url.js) | ||
*/ | ||
declare module "url" { | ||
import { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring'; | ||
import { Blob as NodeBlob } from "node:buffer"; | ||
import { ClientRequestArgs } from "node:http"; | ||
import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; | ||
// Input to `url.format` | ||
interface UrlObject { | ||
auth?: string | null; | ||
hash?: string | null; | ||
host?: string | null; | ||
hostname?: string | null; | ||
href?: string | null; | ||
pathname?: string | null; | ||
protocol?: string | null; | ||
search?: string | null; | ||
slashes?: boolean | null; | ||
port?: string | number | null; | ||
query?: string | null | ParsedUrlQueryInput; | ||
auth?: string | null | undefined; | ||
hash?: string | null | undefined; | ||
host?: string | null | undefined; | ||
hostname?: string | null | undefined; | ||
href?: string | null | undefined; | ||
pathname?: string | null | undefined; | ||
protocol?: string | null | undefined; | ||
search?: string | null | undefined; | ||
slashes?: boolean | null | undefined; | ||
port?: string | number | null | undefined; | ||
query?: string | null | ParsedUrlQueryInput | undefined; | ||
} | ||
// Output of `url.parse` | ||
@@ -34,84 +43,886 @@ interface Url { | ||
} | ||
interface UrlWithParsedQuery extends Url { | ||
query: ParsedUrlQuery; | ||
} | ||
interface UrlWithStringQuery extends Url { | ||
query: string | null; | ||
} | ||
/** @deprecated since v11.0.0 - Use the WHATWG URL API. */ | ||
function parse(urlStr: string): UrlWithStringQuery; | ||
/** @deprecated since v11.0.0 - Use the WHATWG URL API. */ | ||
function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; | ||
/** @deprecated since v11.0.0 - Use the WHATWG URL API. */ | ||
function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; | ||
/** @deprecated since v11.0.0 - Use the WHATWG URL API. */ | ||
function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; | ||
function format(URL: URL, options?: URLFormatOptions): string; | ||
/** @deprecated since v11.0.0 - Use the WHATWG URL API. */ | ||
/** | ||
* The `url.parse()` method takes a URL string, parses it, and returns a URL | ||
* object. | ||
* | ||
* A `TypeError` is thrown if `urlString` is not a string. | ||
* | ||
* A `URIError` is thrown if the `auth` property is present but cannot be decoded. | ||
* | ||
* `url.parse()` uses a lenient, non-standard algorithm for parsing URL | ||
* strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted | ||
* input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. | ||
* @since v0.1.25 | ||
* @deprecated Use the WHATWG URL API instead. | ||
* @param urlString The URL string to parse. | ||
* @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property | ||
* on the returned URL object will be an unparsed, undecoded string. | ||
* @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the | ||
* result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. | ||
*/ | ||
function parse(urlString: string): UrlWithStringQuery; | ||
function parse( | ||
urlString: string, | ||
parseQueryString: false | undefined, | ||
slashesDenoteHost?: boolean, | ||
): UrlWithStringQuery; | ||
function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; | ||
function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; | ||
/** | ||
* The `url.format()` method returns a formatted URL string derived from`urlObject`. | ||
* | ||
* ```js | ||
* const url = require('node:url'); | ||
* url.format({ | ||
* protocol: 'https', | ||
* hostname: 'example.com', | ||
* pathname: '/some/path', | ||
* query: { | ||
* page: 1, | ||
* format: 'json', | ||
* }, | ||
* }); | ||
* | ||
* // => 'https://example.com/some/path?page=1&format=json' | ||
* ``` | ||
* | ||
* If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. | ||
* | ||
* The formatting process operates as follows: | ||
* | ||
* * A new empty string `result` is created. | ||
* * If `urlObject.protocol` is a string, it is appended as-is to `result`. | ||
* * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. | ||
* * For all string values of `urlObject.protocol` that _do not end_ with an ASCII | ||
* colon (`:`) character, the literal string `:` will be appended to `result`. | ||
* * If either of the following conditions is true, then the literal string `//`will be appended to `result`: | ||
* * `urlObject.slashes` property is true; | ||
* * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; | ||
* * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string | ||
* and appended to `result`followed by the literal string `@`. | ||
* * If the `urlObject.host` property is `undefined` then: | ||
* * If the `urlObject.hostname` is a string, it is appended to `result`. | ||
* * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, | ||
* an `Error` is thrown. | ||
* * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: | ||
* * The literal string `:` is appended to `result`, and | ||
* * The value of `urlObject.port` is coerced to a string and appended to`result`. | ||
* * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. | ||
* * If the `urlObject.pathname` property is a string that is not an empty string: | ||
* * If the `urlObject.pathname`_does not start_ with an ASCII forward slash | ||
* (`/`), then the literal string `'/'` is appended to `result`. | ||
* * The value of `urlObject.pathname` is appended to `result`. | ||
* * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. | ||
* * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the | ||
* `querystring` module's `stringify()`method passing the value of `urlObject.query`. | ||
* * Otherwise, if `urlObject.search` is a string: | ||
* * If the value of `urlObject.search`_does not start_ with the ASCII question | ||
* mark (`?`) character, the literal string `?` is appended to `result`. | ||
* * The value of `urlObject.search` is appended to `result`. | ||
* * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. | ||
* * If the `urlObject.hash` property is a string: | ||
* * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) | ||
* character, the literal string `#` is appended to `result`. | ||
* * The value of `urlObject.hash` is appended to `result`. | ||
* * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a | ||
* string, an `Error` is thrown. | ||
* * `result` is returned. | ||
* @since v0.1.25 | ||
* @legacy Use the WHATWG URL API instead. | ||
* @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. | ||
*/ | ||
function format(urlObject: URL, options?: URLFormatOptions): string; | ||
/** | ||
* The `url.format()` method returns a formatted URL string derived from`urlObject`. | ||
* | ||
* ```js | ||
* const url = require('url'); | ||
* url.format({ | ||
* protocol: 'https', | ||
* hostname: 'example.com', | ||
* pathname: '/some/path', | ||
* query: { | ||
* page: 1, | ||
* format: 'json' | ||
* } | ||
* }); | ||
* | ||
* // => 'https://example.com/some/path?page=1&format=json' | ||
* ``` | ||
* | ||
* If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. | ||
* | ||
* The formatting process operates as follows: | ||
* | ||
* * A new empty string `result` is created. | ||
* * If `urlObject.protocol` is a string, it is appended as-is to `result`. | ||
* * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. | ||
* * For all string values of `urlObject.protocol` that _do not end_ with an ASCII | ||
* colon (`:`) character, the literal string `:` will be appended to `result`. | ||
* * If either of the following conditions is true, then the literal string `//`will be appended to `result`: | ||
* * `urlObject.slashes` property is true; | ||
* * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; | ||
* * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string | ||
* and appended to `result`followed by the literal string `@`. | ||
* * If the `urlObject.host` property is `undefined` then: | ||
* * If the `urlObject.hostname` is a string, it is appended to `result`. | ||
* * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, | ||
* an `Error` is thrown. | ||
* * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: | ||
* * The literal string `:` is appended to `result`, and | ||
* * The value of `urlObject.port` is coerced to a string and appended to`result`. | ||
* * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. | ||
* * If the `urlObject.pathname` property is a string that is not an empty string: | ||
* * If the `urlObject.pathname`_does not start_ with an ASCII forward slash | ||
* (`/`), then the literal string `'/'` is appended to `result`. | ||
* * The value of `urlObject.pathname` is appended to `result`. | ||
* * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. | ||
* * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the | ||
* `querystring` module's `stringify()`method passing the value of `urlObject.query`. | ||
* * Otherwise, if `urlObject.search` is a string: | ||
* * If the value of `urlObject.search`_does not start_ with the ASCII question | ||
* mark (`?`) character, the literal string `?` is appended to `result`. | ||
* * The value of `urlObject.search` is appended to `result`. | ||
* * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. | ||
* * If the `urlObject.hash` property is a string: | ||
* * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) | ||
* character, the literal string `#` is appended to `result`. | ||
* * The value of `urlObject.hash` is appended to `result`. | ||
* * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a | ||
* string, an `Error` is thrown. | ||
* * `result` is returned. | ||
* @since v0.1.25 | ||
* @legacy Use the WHATWG URL API instead. | ||
* @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. | ||
*/ | ||
function format(urlObject: UrlObject | string): string; | ||
/** @deprecated since v11.0.0 - Use the WHATWG URL API. */ | ||
/** | ||
* The `url.resolve()` method resolves a target URL relative to a base URL in a | ||
* manner similar to that of a web browser resolving an anchor tag. | ||
* | ||
* ```js | ||
* const url = require('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' | ||
* ``` | ||
* | ||
* To achieve the same result using the WHATWG URL API: | ||
* | ||
* ```js | ||
* function resolve(from, to) { | ||
* const resolvedUrl = new URL(to, new URL(from, 'resolve://')); | ||
* if (resolvedUrl.protocol === 'resolve:') { | ||
* // `from` is a relative URL. | ||
* const { pathname, search, hash } = resolvedUrl; | ||
* return pathname + search + hash; | ||
* } | ||
* return resolvedUrl.toString(); | ||
* } | ||
* | ||
* resolve('/one/two/three', 'four'); // '/one/two/four' | ||
* resolve('http://example.com/', '/one'); // 'http://example.com/one' | ||
* resolve('http://example.com/one', '/two'); // 'http://example.com/two' | ||
* ``` | ||
* @since v0.1.25 | ||
* @legacy Use the WHATWG URL API instead. | ||
* @param from The base URL to use if `to` is a relative URL. | ||
* @param to The target URL to resolve. | ||
*/ | ||
function resolve(from: string, to: string): string; | ||
/** | ||
* Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an | ||
* invalid domain, the empty string is returned. | ||
* | ||
* It performs the inverse operation to {@link domainToUnicode}. | ||
* | ||
* ```js | ||
* import url from 'node:url'; | ||
* | ||
* console.log(url.domainToASCII('español.com')); | ||
* // Prints xn--espaol-zwa.com | ||
* console.log(url.domainToASCII('中文.com')); | ||
* // Prints xn--fiq228c.com | ||
* console.log(url.domainToASCII('xn--iñvalid.com')); | ||
* // Prints an empty string | ||
* ``` | ||
* @since v7.4.0, v6.13.0 | ||
*/ | ||
function domainToASCII(domain: string): string; | ||
/** | ||
* Returns the Unicode serialization of the `domain`. If `domain` is an invalid | ||
* domain, the empty string is returned. | ||
* | ||
* It performs the inverse operation to {@link domainToASCII}. | ||
* | ||
* ```js | ||
* import url from 'node:url'; | ||
* | ||
* console.log(url.domainToUnicode('xn--espaol-zwa.com')); | ||
* // Prints español.com | ||
* console.log(url.domainToUnicode('xn--fiq228c.com')); | ||
* // Prints 中文.com | ||
* console.log(url.domainToUnicode('xn--iñvalid.com')); | ||
* // Prints an empty string | ||
* ``` | ||
* @since v7.4.0, v6.13.0 | ||
*/ | ||
function domainToUnicode(domain: string): string; | ||
/** | ||
* This function ensures the correct decodings of percent-encoded characters as | ||
* well as ensuring a cross-platform valid absolute path string. | ||
* | ||
* ```js | ||
* import { fileURLToPath } from 'node:url'; | ||
* | ||
* const __filename = fileURLToPath(import.meta.url); | ||
* | ||
* new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ | ||
* fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) | ||
* | ||
* new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt | ||
* fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) | ||
* | ||
* new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt | ||
* fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) | ||
* | ||
* new URL('file:///hello world').pathname; // Incorrect: /hello%20world | ||
* fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) | ||
* ``` | ||
* @since v10.12.0 | ||
* @param url The file URL string or URL object to convert to a path. | ||
* @return The fully-resolved platform-specific Node.js file path. | ||
*/ | ||
function fileURLToPath(url: string | URL): string; | ||
/** | ||
* This function ensures that path is resolved absolutely, and that the URL | ||
* This function ensures that `path` is resolved absolutely, and that the URL | ||
* control characters are correctly encoded when converting into a File URL. | ||
* @param url The path to convert to a File URL. | ||
* | ||
* ```js | ||
* import { pathToFileURL } from 'node:url'; | ||
* | ||
* new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 | ||
* pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) | ||
* | ||
* new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c | ||
* pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) | ||
* ``` | ||
* @since v10.12.0 | ||
* @param path The path to convert to a File URL. | ||
* @return The file URL object. | ||
*/ | ||
function pathToFileURL(url: string): URL; | ||
function pathToFileURL(path: string): URL; | ||
/** | ||
* This utility function converts a URL object into an ordinary options object as | ||
* expected by the `http.request()` and `https.request()` APIs. | ||
* | ||
* ```js | ||
* import { urlToHttpOptions } from 'node:url'; | ||
* const myURL = new URL('https://a:b@測試?abc#foo'); | ||
* | ||
* console.log(urlToHttpOptions(myURL)); | ||
* /* | ||
* { | ||
* protocol: 'https:', | ||
* hostname: 'xn--g6w251d', | ||
* hash: '#foo', | ||
* search: '?abc', | ||
* pathname: '/', | ||
* path: '/?abc', | ||
* href: 'https://a:b@xn--g6w251d/?abc#foo', | ||
* auth: 'a:b' | ||
* } | ||
* | ||
* ``` | ||
* @since v15.7.0, v14.18.0 | ||
* @param url The `WHATWG URL` object to convert to an options object. | ||
* @return Options object | ||
*/ | ||
function urlToHttpOptions(url: URL): ClientRequestArgs; | ||
interface URLFormatOptions { | ||
auth?: boolean; | ||
fragment?: boolean; | ||
search?: boolean; | ||
unicode?: boolean; | ||
auth?: boolean | undefined; | ||
fragment?: boolean | undefined; | ||
search?: boolean | undefined; | ||
unicode?: boolean | undefined; | ||
} | ||
/** | ||
* Browser-compatible `URL` class, implemented by following the WHATWG URL | ||
* Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. | ||
* The `URL` class is also available on the global object. | ||
* | ||
* In accordance with browser conventions, all properties of `URL` objects | ||
* are implemented as getters and setters on the class prototype, rather than as | ||
* data properties on the object itself. Thus, unlike `legacy urlObject` s, | ||
* using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still | ||
* return `true`. | ||
* @since v7.0.0, v6.13.0 | ||
*/ | ||
class URL { | ||
/** | ||
* Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. | ||
* | ||
* ```js | ||
* const { | ||
* Blob, | ||
* resolveObjectURL, | ||
* } = require('node:buffer'); | ||
* | ||
* const blob = new Blob(['hello']); | ||
* const id = URL.createObjectURL(blob); | ||
* | ||
* // later... | ||
* | ||
* const otherBlob = resolveObjectURL(id); | ||
* console.log(otherBlob.size); | ||
* ``` | ||
* | ||
* The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. | ||
* | ||
* `Blob` objects are registered within the current thread. If using Worker | ||
* 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(objectUrl: string): void; | ||
/** | ||
* Checks if an `input` relative to the `base` can be parsed to a `URL`. | ||
* | ||
* ```js | ||
* const isValid = URL.canParse('/foo', 'https://example.org/'); // true | ||
* | ||
* const isNotValid = URL.canParse('/foo'); // false | ||
* ``` | ||
* @since v19.9.0 | ||
* @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is | ||
* `converted to a string` first. | ||
* @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. | ||
*/ | ||
static canParse(input: string, base?: string): boolean; | ||
constructor(input: string, base?: string | URL); | ||
/** | ||
* Gets and sets the fragment portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/foo#bar'); | ||
* console.log(myURL.hash); | ||
* // Prints #bar | ||
* | ||
* myURL.hash = 'baz'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/foo#baz | ||
* ``` | ||
* | ||
* Invalid URL characters included in the value assigned to the `hash` property | ||
* are `percent-encoded`. The selection of which characters to | ||
* percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. | ||
*/ | ||
hash: string; | ||
/** | ||
* Gets and sets the host portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org:81/foo'); | ||
* console.log(myURL.host); | ||
* // Prints example.org:81 | ||
* | ||
* myURL.host = 'example.com:82'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.com:82/foo | ||
* ``` | ||
* | ||
* Invalid host values assigned to the `host` property are ignored. | ||
*/ | ||
host: string; | ||
/** | ||
* Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the | ||
* port. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org:81/foo'); | ||
* console.log(myURL.hostname); | ||
* // Prints example.org | ||
* | ||
* // Setting the hostname does not change the port | ||
* myURL.hostname = 'example.com'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.com:81/foo | ||
* | ||
* // Use myURL.host to change the hostname and port | ||
* myURL.host = 'example.org:82'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.org:82/foo | ||
* ``` | ||
* | ||
* Invalid host name values assigned to the `hostname` property are ignored. | ||
*/ | ||
hostname: string; | ||
/** | ||
* Gets and sets the serialized URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/foo'); | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/foo | ||
* | ||
* myURL.href = 'https://example.com/bar'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.com/bar | ||
* ``` | ||
* | ||
* Getting the value of the `href` property is equivalent to calling {@link toString}. | ||
* | ||
* Setting the value of this property to a new value is equivalent to creating a | ||
* new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. | ||
* | ||
* If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. | ||
*/ | ||
href: string; | ||
/** | ||
* Gets the read-only serialization of the URL's origin. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/foo/bar?baz'); | ||
* console.log(myURL.origin); | ||
* // Prints https://example.org | ||
* ``` | ||
* | ||
* ```js | ||
* const idnURL = new URL('https://測試'); | ||
* console.log(idnURL.origin); | ||
* // Prints https://xn--g6w251d | ||
* | ||
* console.log(idnURL.hostname); | ||
* // Prints xn--g6w251d | ||
* ``` | ||
*/ | ||
readonly origin: string; | ||
/** | ||
* Gets and sets the password portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://abc:xyz@example.com'); | ||
* console.log(myURL.password); | ||
* // Prints xyz | ||
* | ||
* myURL.password = '123'; | ||
* console.log(myURL.href); | ||
* // Prints https://abc:123@example.com/ | ||
* ``` | ||
* | ||
* Invalid URL characters included in the value assigned to the `password` property | ||
* are `percent-encoded`. The selection of which characters to | ||
* percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. | ||
*/ | ||
password: string; | ||
/** | ||
* Gets and sets the path portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/abc/xyz?123'); | ||
* console.log(myURL.pathname); | ||
* // Prints /abc/xyz | ||
* | ||
* myURL.pathname = '/abcdef'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/abcdef?123 | ||
* ``` | ||
* | ||
* Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters | ||
* to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. | ||
*/ | ||
pathname: string; | ||
/** | ||
* Gets and sets the port portion of the URL. | ||
* | ||
* The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will | ||
* result in the `port` value becoming | ||
* the empty string (`''`). | ||
* | ||
* The port value can be an empty string in which case the port depends on | ||
* the protocol/scheme: | ||
* | ||
* <omitted> | ||
* | ||
* Upon assigning a value to the port, the value will first be converted to a | ||
* string using `.toString()`. | ||
* | ||
* If that string is invalid but it begins with a number, the leading number is | ||
* assigned to `port`. | ||
* If the number lies outside the range denoted above, it is ignored. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org:8888'); | ||
* console.log(myURL.port); | ||
* // Prints 8888 | ||
* | ||
* // Default ports are automatically transformed to the empty string | ||
* // (HTTPS protocol's default port is 443) | ||
* myURL.port = '443'; | ||
* console.log(myURL.port); | ||
* // Prints the empty string | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/ | ||
* | ||
* myURL.port = 1234; | ||
* console.log(myURL.port); | ||
* // Prints 1234 | ||
* console.log(myURL.href); | ||
* // Prints https://example.org:1234/ | ||
* | ||
* // Completely invalid port strings are ignored | ||
* myURL.port = 'abcd'; | ||
* console.log(myURL.port); | ||
* // Prints 1234 | ||
* | ||
* // Leading numbers are treated as a port number | ||
* myURL.port = '5678abcd'; | ||
* console.log(myURL.port); | ||
* // Prints 5678 | ||
* | ||
* // Non-integers are truncated | ||
* myURL.port = 1234.5678; | ||
* console.log(myURL.port); | ||
* // Prints 1234 | ||
* | ||
* // Out-of-range numbers which are not represented in scientific notation | ||
* // will be ignored. | ||
* myURL.port = 1e10; // 10000000000, will be range-checked as described below | ||
* console.log(myURL.port); | ||
* // Prints 1234 | ||
* ``` | ||
* | ||
* Numbers which contain a decimal point, | ||
* such as floating-point numbers or numbers in scientific notation, | ||
* are not an exception to this rule. | ||
* Leading numbers up to the decimal point will be set as the URL's port, | ||
* assuming they are valid: | ||
* | ||
* ```js | ||
* myURL.port = 4.567e21; | ||
* console.log(myURL.port); | ||
* // Prints 4 (because it is the leading number in the string '4.567e21') | ||
* ``` | ||
*/ | ||
port: string; | ||
/** | ||
* Gets and sets the protocol portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org'); | ||
* console.log(myURL.protocol); | ||
* // Prints https: | ||
* | ||
* myURL.protocol = 'ftp'; | ||
* console.log(myURL.href); | ||
* // Prints ftp://example.org/ | ||
* ``` | ||
* | ||
* Invalid URL protocol values assigned to the `protocol` property are ignored. | ||
*/ | ||
protocol: string; | ||
/** | ||
* Gets and sets the serialized query portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/abc?123'); | ||
* console.log(myURL.search); | ||
* // Prints ?123 | ||
* | ||
* myURL.search = 'abc=xyz'; | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/abc?abc=xyz | ||
* ``` | ||
* | ||
* Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which | ||
* characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. | ||
*/ | ||
search: string; | ||
/** | ||
* Gets the `URLSearchParams` object representing the query parameters of the | ||
* URL. This property is read-only but the `URLSearchParams` object it provides | ||
* can be used to mutate the URL instance; to replace the entirety of query | ||
* parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. | ||
* | ||
* Use care when using `.searchParams` to modify the `URL` because, | ||
* per the WHATWG specification, the `URLSearchParams` object uses | ||
* different rules to determine which characters to percent-encode. For | ||
* instance, the `URL` object will not percent encode the ASCII tilde (`~`) | ||
* character, while `URLSearchParams` will always encode it: | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/abc?foo=~bar'); | ||
* | ||
* console.log(myURL.search); // prints ?foo=~bar | ||
* | ||
* // Modify the URL via searchParams... | ||
* myURL.searchParams.sort(); | ||
* | ||
* console.log(myURL.search); // prints ?foo=%7Ebar | ||
* ``` | ||
*/ | ||
readonly searchParams: URLSearchParams; | ||
/** | ||
* Gets and sets the username portion of the URL. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://abc:xyz@example.com'); | ||
* console.log(myURL.username); | ||
* // Prints abc | ||
* | ||
* myURL.username = '123'; | ||
* console.log(myURL.href); | ||
* // Prints https://123:xyz@example.com/ | ||
* ``` | ||
* | ||
* Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which | ||
* characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. | ||
*/ | ||
username: string; | ||
/** | ||
* The `toString()` method on the `URL` object returns the serialized URL. The | ||
* value returned is equivalent to that of {@link href} and {@link toJSON}. | ||
*/ | ||
toString(): string; | ||
/** | ||
* The `toJSON()` method on the `URL` object returns the serialized URL. The | ||
* value returned is equivalent to that of {@link href} and {@link toString}. | ||
* | ||
* This method is automatically called when an `URL` object is serialized | ||
* with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). | ||
* | ||
* ```js | ||
* const myURLs = [ | ||
* new URL('https://www.example.com'), | ||
* new URL('https://test.example.org'), | ||
* ]; | ||
* console.log(JSON.stringify(myURLs)); | ||
* // Prints ["https://www.example.com/","https://test.example.org/"] | ||
* ``` | ||
*/ | ||
toJSON(): string; | ||
} | ||
/** | ||
* 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. | ||
* The `URLSearchParams` class is also available on the global object. | ||
* | ||
* The WHATWG `URLSearchParams` interface and the `querystring` module have | ||
* similar purpose, but the purpose of the `querystring` module is more | ||
* general, as it allows the customization of delimiter characters (`&` and `=`). | ||
* On the other hand, this API is designed purely for URL query strings. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/?abc=123'); | ||
* console.log(myURL.searchParams.get('abc')); | ||
* // Prints 123 | ||
* | ||
* myURL.searchParams.append('abc', 'xyz'); | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/?abc=123&abc=xyz | ||
* | ||
* myURL.searchParams.delete('abc'); | ||
* myURL.searchParams.set('a', 'b'); | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/?a=b | ||
* | ||
* const newSearchParams = new URLSearchParams(myURL.searchParams); | ||
* // The above is equivalent to | ||
* // const newSearchParams = new URLSearchParams(myURL.search); | ||
* | ||
* newSearchParams.append('a', 'c'); | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/?a=b | ||
* console.log(newSearchParams.toString()); | ||
* // Prints a=b&a=c | ||
* | ||
* // newSearchParams.toString() is implicitly called | ||
* myURL.search = newSearchParams; | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/?a=b&a=c | ||
* newSearchParams.delete('a'); | ||
* console.log(myURL.href); | ||
* // Prints https://example.org/?a=b&a=c | ||
* ``` | ||
* @since v7.5.0, v6.13.0 | ||
*/ | ||
class URLSearchParams implements Iterable<[string, string]> { | ||
constructor(init?: URLSearchParams | string | NodeJS.Dict<string | ReadonlyArray<string>> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); | ||
constructor( | ||
init?: | ||
| URLSearchParams | ||
| string | ||
| Record<string, string | readonly string[]> | ||
| Iterable<[string, string]> | ||
| ReadonlyArray<[string, string]>, | ||
); | ||
/** | ||
* Append a new name-value pair to the query string. | ||
*/ | ||
append(name: string, value: string): void; | ||
delete(name: string): void; | ||
/** | ||
* If `value` is provided, removes all name-value pairs | ||
* where name is `name` and value is `value`.. | ||
* | ||
* If `value` is not provided, removes all name-value pairs whose name is `name`. | ||
*/ | ||
delete(name: string, value?: string): void; | ||
/** | ||
* Returns an ES6 `Iterator` over each of the name-value pairs in the query. | ||
* Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. | ||
* | ||
* Alias for `urlSearchParams[@@iterator]()`. | ||
*/ | ||
entries(): IterableIterator<[string, string]>; | ||
forEach(callback: (value: string, name: string, searchParams: this) => void): void; | ||
/** | ||
* Iterates over each name-value pair in the query and invokes the given function. | ||
* | ||
* ```js | ||
* const myURL = new URL('https://example.org/?a=b&c=d'); | ||
* myURL.searchParams.forEach((value, name, searchParams) => { | ||
* console.log(name, value, myURL.searchParams === searchParams); | ||
* }); | ||
* // Prints: | ||
* // a b true | ||
* // c d true | ||
* ``` | ||
* @param fn Invoked for each name-value pair in the query | ||
* @param thisArg To be used as `this` value for when `fn` is called | ||
*/ | ||
forEach<TThis = this>( | ||
callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, | ||
thisArg?: TThis, | ||
): void; | ||
/** | ||
* Returns the value of the first name-value pair whose name is `name`. If there | ||
* are no such pairs, `null` is returned. | ||
* @return or `null` if there is no name-value pair with the given `name`. | ||
*/ | ||
get(name: string): string | null; | ||
/** | ||
* Returns the values of all name-value pairs whose name is `name`. If there are | ||
* no such pairs, an empty array is returned. | ||
*/ | ||
getAll(name: string): string[]; | ||
has(name: string): boolean; | ||
/** | ||
* Checks if the `URLSearchParams` object contains key-value pair(s) based on`name` and an optional `value` argument. | ||
* | ||
* If `value` is provided, returns `true` when name-value pair with | ||
* same `name` and `value` exists. | ||
* | ||
* If `value` is not provided, returns `true` if there is at least one name-value | ||
* pair whose name is `name`. | ||
*/ | ||
has(name: string, value?: string): boolean; | ||
/** | ||
* Returns an ES6 `Iterator` over the names of each name-value pair. | ||
* | ||
* ```js | ||
* const params = new URLSearchParams('foo=bar&foo=baz'); | ||
* for (const name of params.keys()) { | ||
* console.log(name); | ||
* } | ||
* // Prints: | ||
* // foo | ||
* // foo | ||
* ``` | ||
*/ | ||
keys(): IterableIterator<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, | ||
* append the name-value pair to the query string. | ||
* | ||
* ```js | ||
* const params = new URLSearchParams(); | ||
* params.append('foo', 'bar'); | ||
* params.append('foo', 'baz'); | ||
* params.append('abc', 'def'); | ||
* console.log(params.toString()); | ||
* // Prints foo=bar&foo=baz&abc=def | ||
* | ||
* params.set('foo', 'def'); | ||
* params.set('xyz', 'opq'); | ||
* console.log(params.toString()); | ||
* // Prints foo=def&abc=def&xyz=opq | ||
* ``` | ||
*/ | ||
set(name: string, value: string): void; | ||
/** | ||
* The total number of parameter entries. | ||
* @since v19.8.0 | ||
*/ | ||
readonly size: number; | ||
/** | ||
* Sort all existing name-value pairs in-place by their names. Sorting is done | ||
* with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs | ||
* with the same name is preserved. | ||
* | ||
* This method can be used, in particular, to increase cache hits. | ||
* | ||
* ```js | ||
* const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); | ||
* params.sort(); | ||
* console.log(params.toString()); | ||
* // Prints query%5B%5D=abc&query%5B%5D=123&type=search | ||
* ``` | ||
* @since v7.7.0, v6.13.0 | ||
*/ | ||
sort(): void; | ||
/** | ||
* Returns the search parameters serialized as a string, with characters | ||
* percent-encoded where necessary. | ||
*/ | ||
toString(): string; | ||
/** | ||
* Returns an ES6 `Iterator` over the values of each name-value pair. | ||
*/ | ||
values(): IterableIterator<string>; | ||
[Symbol.iterator](): IterableIterator<[string, string]>; | ||
} | ||
import { URL as _URL, 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 | ||
*/ | ||
var URLSearchParams: typeof globalThis extends { | ||
onmessage: any; | ||
URLSearchParams: infer T; | ||
} ? T | ||
: typeof _URLSearchParams; | ||
} | ||
} | ||
declare module "node:url" { | ||
export * from "url"; | ||
} |
594
node/v8.d.ts
@@ -0,4 +1,11 @@ | ||
/** | ||
* 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'); | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/v8.js) | ||
*/ | ||
declare module "v8" { | ||
import { Readable } from "stream"; | ||
import { Readable } from "node:stream"; | ||
interface HeapSpaceInfo { | ||
@@ -11,6 +18,4 @@ space_name: string; | ||
} | ||
// ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ | ||
type DoesZapCodeSpaceFlag = 0 | 1; | ||
interface HeapInfo { | ||
@@ -28,4 +33,6 @@ total_heap_size: number; | ||
number_of_detached_contexts: number; | ||
total_global_handles_size: number; | ||
used_global_handles_size: number; | ||
external_memory: number; | ||
} | ||
interface HeapCodeStatistics { | ||
@@ -36,11 +43,134 @@ code_and_metadata_size: number; | ||
} | ||
/** | ||
* Returns an integer representing a "version tag" derived from the V8 version, command line flags and detected CPU features. | ||
* This is useful for determining whether a vm.Script cachedData buffer is compatible with this instance of V8. | ||
* Returns an integer representing a version tag derived from the V8 version, | ||
* command-line flags, and detected CPU features. This is useful for determining | ||
* whether a `vm.Script` `cachedData` buffer is compatible with this instance | ||
* of V8. | ||
* | ||
* ```js | ||
* console.log(v8.cachedDataVersionTag()); // 3947234607 | ||
* // The value returned by v8.cachedDataVersionTag() is derived from the V8 | ||
* // version, command-line flags, and detected CPU features. Test that the value | ||
* // does indeed update when flags are toggled. | ||
* v8.setFlagsFromString('--allow_natives_syntax'); | ||
* console.log(v8.cachedDataVersionTag()); // 183726201 | ||
* ``` | ||
* @since v8.0.0 | ||
*/ | ||
function cachedDataVersionTag(): number; | ||
/** | ||
* Returns an object with the following properties: | ||
* | ||
* `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap | ||
* garbage with a bit pattern. The RSS footprint (resident set size) gets bigger | ||
* because it continuously touches all heap pages and that makes them less likely | ||
* to get swapped out by the operating system. | ||
* | ||
* `number_of_native_contexts` The value of native\_context is the number of the | ||
* top-level contexts currently active. Increase of this number over time indicates | ||
* a memory leak. | ||
* | ||
* `number_of_detached_contexts` The value of detached\_context is the number | ||
* of contexts that were detached and not yet garbage collected. This number | ||
* being non-zero indicates a potential memory leak. | ||
* | ||
* `total_global_handles_size` The value of total\_global\_handles\_size is the | ||
* total memory size of V8 global handles. | ||
* | ||
* `used_global_handles_size` The value of used\_global\_handles\_size is the | ||
* used memory size of V8 global handles. | ||
* | ||
* `external_memory` The value of external\_memory is the memory size of array | ||
* buffers and external strings. | ||
* | ||
* ```js | ||
* { | ||
* total_heap_size: 7326976, | ||
* total_heap_size_executable: 4194304, | ||
* total_physical_size: 7326976, | ||
* total_available_size: 1152656, | ||
* used_heap_size: 3476208, | ||
* heap_size_limit: 1535115264, | ||
* malloced_memory: 16384, | ||
* peak_malloced_memory: 1127496, | ||
* does_zap_garbage: 0, | ||
* number_of_native_contexts: 1, | ||
* number_of_detached_contexts: 0, | ||
* total_global_handles_size: 8192, | ||
* used_global_handles_size: 3296, | ||
* external_memory: 318824 | ||
* } | ||
* ``` | ||
* @since v1.0.0 | ||
*/ | ||
function getHeapStatistics(): HeapInfo; | ||
/** | ||
* 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 | ||
* heap space can be guaranteed as the statistics are provided via the | ||
* V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the | ||
* next. | ||
* | ||
* The value returned is an array of objects containing the following properties: | ||
* | ||
* ```json | ||
* [ | ||
* { | ||
* "space_name": "new_space", | ||
* "space_size": 2063872, | ||
* "space_used_size": 951112, | ||
* "space_available_size": 80824, | ||
* "physical_space_size": 2063872 | ||
* }, | ||
* { | ||
* "space_name": "old_space", | ||
* "space_size": 3090560, | ||
* "space_used_size": 2493792, | ||
* "space_available_size": 0, | ||
* "physical_space_size": 3090560 | ||
* }, | ||
* { | ||
* "space_name": "code_space", | ||
* "space_size": 1260160, | ||
* "space_used_size": 644256, | ||
* "space_available_size": 960, | ||
* "physical_space_size": 1260160 | ||
* }, | ||
* { | ||
* "space_name": "map_space", | ||
* "space_size": 1094160, | ||
* "space_used_size": 201608, | ||
* "space_available_size": 0, | ||
* "physical_space_size": 1094160 | ||
* }, | ||
* { | ||
* "space_name": "large_object_space", | ||
* "space_size": 0, | ||
* "space_used_size": 0, | ||
* "space_available_size": 1490980608, | ||
* "physical_space_size": 0 | ||
* } | ||
* ] | ||
* ``` | ||
* @since v6.0.0 | ||
*/ | ||
function getHeapSpaceStatistics(): HeapSpaceInfo[]; | ||
/** | ||
* The `v8.setFlagsFromString()` method can be used to programmatically set | ||
* V8 command-line flags. This method should be used with care. Changing settings | ||
* after the VM has started may result in unpredictable behavior, including | ||
* crashes and data loss; or it may simply do nothing. | ||
* | ||
* The V8 options available for a version of Node.js may be determined by running`node --v8-options`. | ||
* | ||
* Usage: | ||
* | ||
* ```js | ||
* // Print GC events to stdout for one minute. | ||
* const v8 = require('node:v8'); | ||
* v8.setFlagsFromString('--trace_gc'); | ||
* setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); | ||
* ``` | ||
* @since v1.0.0 | ||
*/ | ||
function setFlagsFromString(flags: string): void; | ||
@@ -50,22 +180,94 @@ /** | ||
* Stream that may be used to read the JSON serialized representation. | ||
* This conversation was marked as resolved by joyeecheung | ||
* This JSON stream format is intended to be used with tools such as | ||
* Chrome DevTools. The JSON schema is undocumented and specific to the | ||
* V8 engine, and may change from one version of V8 to the next. | ||
* V8 engine. Therefore, the schema may change from one version of V8 to the next. | ||
* | ||
* Creating a heap snapshot requires memory about twice the size of the heap at | ||
* the time the snapshot is created. This results in the risk of OOM killers | ||
* terminating the process. | ||
* | ||
* Generating a snapshot is a synchronous operation which blocks the event loop | ||
* for a duration depending on the heap size. | ||
* | ||
* ```js | ||
* // Print heap snapshot to the console | ||
* const v8 = require('node:v8'); | ||
* const stream = v8.getHeapSnapshot(); | ||
* stream.pipe(process.stdout); | ||
* ``` | ||
* @since v11.13.0 | ||
* @return A Readable containing the V8 heap snapshot. | ||
*/ | ||
function getHeapSnapshot(): Readable; | ||
/** | ||
* Generates a snapshot of the current V8 heap and writes it to a JSON | ||
* file. This file is intended to be used with tools such as Chrome | ||
* DevTools. The JSON schema is undocumented and specific to the V8 | ||
* engine, and may change from one version of V8 to the next. | ||
* | ||
* @param fileName The file path where the V8 heap snapshot is to be | ||
* saved. If not specified, a file name with the pattern | ||
* `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be | ||
* generated, where `{pid}` will be the PID of the Node.js process, | ||
* `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from | ||
* the main Node.js thread or the id of a worker thread. | ||
* A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will | ||
* not contain any information about the workers, and vice versa. | ||
* | ||
* Creating a heap snapshot requires memory about twice the size of the heap at | ||
* the time the snapshot is created. This results in the risk of OOM killers | ||
* terminating the process. | ||
* | ||
* Generating a snapshot is a synchronous operation which blocks the event loop | ||
* for a duration depending on the heap size. | ||
* | ||
* ```js | ||
* const { writeHeapSnapshot } = require('node:v8'); | ||
* const { | ||
* Worker, | ||
* isMainThread, | ||
* parentPort, | ||
* } = require('node:worker_threads'); | ||
* | ||
* if (isMainThread) { | ||
* const worker = new Worker(__filename); | ||
* | ||
* worker.once('message', (filename) => { | ||
* console.log(`worker heapdump: ${filename}`); | ||
* // Now get a heapdump for the main thread. | ||
* console.log(`main thread heapdump: ${writeHeapSnapshot()}`); | ||
* }); | ||
* | ||
* // Tell the worker to create a heapdump. | ||
* worker.postMessage('heapdump'); | ||
* } else { | ||
* parentPort.once('message', (message) => { | ||
* if (message === 'heapdump') { | ||
* // Generate a heapdump for the worker | ||
* // and return the filename to the parent. | ||
* parentPort.postMessage(writeHeapSnapshot()); | ||
* } | ||
* }); | ||
* } | ||
* ``` | ||
* @since v11.13.0 | ||
* @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be | ||
* generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a | ||
* worker thread. | ||
* @return The filename where the snapshot was saved. | ||
*/ | ||
function writeHeapSnapshot(fileName?: string): string; | ||
function writeHeapSnapshot(filename?: string): string; | ||
/** | ||
* Get statistics about code and its metadata in the heap, see | ||
* V8[`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the | ||
* following properties: | ||
* | ||
* ```js | ||
* { | ||
* code_and_metadata_size: 212208, | ||
* bytecode_and_metadata_size: 161368, | ||
* external_script_source_size: 1410794, | ||
* cpu_profiler_metadata_size: 0, | ||
* } | ||
* ``` | ||
* @since v12.8.0 | ||
*/ | ||
function getHeapCodeStatistics(): HeapCodeStatistics; | ||
/** | ||
* @since v8.0.0 | ||
*/ | ||
class Serializer { | ||
@@ -76,51 +278,53 @@ /** | ||
writeHeader(): void; | ||
/** | ||
* Serializes a JavaScript value and adds the serialized representation to the internal buffer. | ||
* This throws an error if value cannot be serialized. | ||
* Serializes a JavaScript value and adds the serialized representation to the | ||
* internal buffer. | ||
* | ||
* This throws an error if `value` cannot be serialized. | ||
*/ | ||
writeValue(val: any): boolean; | ||
/** | ||
* Returns the stored internal buffer. | ||
* This serializer should not be used once the buffer is released. | ||
* Calling this method results in undefined behavior if a previous write has failed. | ||
* Returns the stored internal buffer. This serializer should not be used once | ||
* the buffer is released. Calling this method results in undefined behavior | ||
* if a previous write has failed. | ||
*/ | ||
releaseBuffer(): Buffer; | ||
/** | ||
* Marks an ArrayBuffer as having its contents transferred out of band.\ | ||
* Pass the corresponding ArrayBuffer in the deserializing context to deserializer.transferArrayBuffer(). | ||
* Marks an `ArrayBuffer` as having its contents transferred out of band. | ||
* Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. | ||
* @param id A 32-bit unsigned integer. | ||
* @param arrayBuffer An `ArrayBuffer` instance. | ||
*/ | ||
transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; | ||
/** | ||
* Write a raw 32-bit unsigned integer. | ||
* For use inside of a custom `serializer._writeHostObject()`. | ||
*/ | ||
writeUint32(value: number): void; | ||
/** | ||
* Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. | ||
* For use inside of a custom `serializer._writeHostObject()`. | ||
*/ | ||
writeUint64(hi: number, lo: number): void; | ||
/** | ||
* Write a JS number value. | ||
* Write a JS `number` value. | ||
* For use inside of a custom `serializer._writeHostObject()`. | ||
*/ | ||
writeDouble(value: number): void; | ||
/** | ||
* Write raw bytes into the serializer’s internal buffer. | ||
* The deserializer will require a way to compute the length of the buffer. | ||
* Write raw bytes into the serializer's internal buffer. The deserializer | ||
* will require a way to compute the length of the buffer. | ||
* For use inside of a custom `serializer._writeHostObject()`. | ||
*/ | ||
writeRawBytes(buffer: NodeJS.TypedArray): void; | ||
} | ||
/** | ||
* A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects, | ||
* and only stores the part of their underlying `ArrayBuffers` that they are referring to. | ||
* A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only | ||
* stores the part of their underlying `ArrayBuffer`s that they are referring to. | ||
* @since v8.0.0 | ||
*/ | ||
class DefaultSerializer extends Serializer { | ||
} | ||
class DefaultSerializer extends Serializer {} | ||
/** | ||
* @since v8.0.0 | ||
*/ | ||
class Deserializer { | ||
@@ -130,7 +334,6 @@ constructor(data: NodeJS.TypedArray); | ||
* Reads and validates a header (including the format version). | ||
* May, for example, reject an invalid or unsupported wire format. | ||
* In that case, an Error is thrown. | ||
* May, for example, reject an invalid or unsupported wire format. In that case, | ||
* an `Error` is thrown. | ||
*/ | ||
readHeader(): boolean; | ||
/** | ||
@@ -140,55 +343,300 @@ * Deserializes a JavaScript value from the buffer and returns it. | ||
readValue(): any; | ||
/** | ||
* Marks an ArrayBuffer as having its contents transferred out of band. | ||
* Pass the corresponding `ArrayBuffer` in the serializing context to serializer.transferArrayBuffer() | ||
* (or return the id from serializer._getSharedArrayBufferId() in the case of SharedArrayBuffers). | ||
* Marks an `ArrayBuffer` as having its contents transferred out of band. | ||
* Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of | ||
* `SharedArrayBuffer`s). | ||
* @param id A 32-bit unsigned integer. | ||
* @param arrayBuffer An `ArrayBuffer` instance. | ||
*/ | ||
transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; | ||
/** | ||
* Reads the underlying wire format version. | ||
* Likely mostly to be useful to legacy code reading old wire format versions. | ||
* May not be called before .readHeader(). | ||
* Reads the underlying wire format version. Likely mostly to be useful to | ||
* legacy code reading old wire format versions. May not be called before`.readHeader()`. | ||
*/ | ||
getWireFormatVersion(): number; | ||
/** | ||
* Read a raw 32-bit unsigned integer and return it. | ||
* For use inside of a custom `deserializer._readHostObject()`. | ||
*/ | ||
readUint32(): number; | ||
/** | ||
* Read a raw 64-bit unsigned integer and return it as an array [hi, lo] with two 32-bit unsigned integer entries. | ||
* Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. | ||
* For use inside of a custom `deserializer._readHostObject()`. | ||
*/ | ||
readUint64(): [number, number]; | ||
/** | ||
* Read a JS number value. | ||
* Read a JS `number` value. | ||
* For use inside of a custom `deserializer._readHostObject()`. | ||
*/ | ||
readDouble(): number; | ||
/** | ||
* Read raw bytes from the deserializer’s internal buffer. | ||
* The length parameter must correspond to the length of the buffer that was passed to serializer.writeRawBytes(). | ||
* Read raw bytes from the deserializer's internal buffer. The `length` parameter | ||
* must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. | ||
* For use inside of a custom `deserializer._readHostObject()`. | ||
*/ | ||
readRawBytes(length: number): Buffer; | ||
} | ||
/** | ||
* A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects, | ||
* and only stores the part of their underlying `ArrayBuffers` that they are referring to. | ||
* A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. | ||
* @since v8.0.0 | ||
*/ | ||
class DefaultDeserializer extends Deserializer { | ||
} | ||
class DefaultDeserializer extends Deserializer {} | ||
/** | ||
* Uses a `DefaultSerializer` to serialize value into a buffer. | ||
* Uses a `DefaultSerializer` to serialize `value` into a buffer. | ||
* | ||
* `ERR_BUFFER_TOO_LARGE` will be thrown when trying to | ||
* serialize a huge object which requires buffer | ||
* larger than `buffer.constants.MAX_LENGTH`. | ||
* @since v8.0.0 | ||
*/ | ||
function serialize(value: any): Buffer; | ||
/** | ||
* Uses a `DefaultDeserializer` with default options to read a JS value from a buffer. | ||
* Uses a `DefaultDeserializer` with default options to read a JS value | ||
* from a buffer. | ||
* @since v8.0.0 | ||
* @param buffer A buffer returned by {@link serialize}. | ||
*/ | ||
function deserialize(data: NodeJS.TypedArray): any; | ||
function deserialize(buffer: NodeJS.TypedArray): 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 | ||
* be reset and a new coverage report will be written to the directory specified | ||
* by `NODE_V8_COVERAGE`. | ||
* | ||
* When the process is about to exit, one last coverage will still be written to | ||
* disk unless {@link stopCoverage} is invoked before the process exits. | ||
* @since v15.1.0, v14.18.0, v12.22.0 | ||
*/ | ||
function takeCoverage(): void; | ||
/** | ||
* The `v8.stopCoverage()` method allows the user to stop the coverage collection | ||
* started by `NODE_V8_COVERAGE`, so that V8 can release the execution count | ||
* records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. | ||
* @since v15.1.0, v14.18.0, v12.22.0 | ||
*/ | ||
function stopCoverage(): void; | ||
/** | ||
* This API collects GC data in current thread. | ||
* @since v19.6.0, v18.15.0 | ||
*/ | ||
class GCProfiler { | ||
/** | ||
* Start collecting GC data. | ||
* @since v19.6.0, v18.15.0 | ||
*/ | ||
start(): void; | ||
/** | ||
* Stop collecting GC data and return an object.The content of object | ||
* is as follows. | ||
* | ||
* ```json | ||
* { | ||
* "version": 1, | ||
* "startTime": 1674059033862, | ||
* "statistics": [ | ||
* { | ||
* "gcType": "Scavenge", | ||
* "beforeGC": { | ||
* "heapStatistics": { | ||
* "totalHeapSize": 5005312, | ||
* "totalHeapSizeExecutable": 524288, | ||
* "totalPhysicalSize": 5226496, | ||
* "totalAvailableSize": 4341325216, | ||
* "totalGlobalHandlesSize": 8192, | ||
* "usedGlobalHandlesSize": 2112, | ||
* "usedHeapSize": 4883840, | ||
* "heapSizeLimit": 4345298944, | ||
* "mallocedMemory": 254128, | ||
* "externalMemory": 225138, | ||
* "peakMallocedMemory": 181760 | ||
* }, | ||
* "heapSpaceStatistics": [ | ||
* { | ||
* "spaceName": "read_only_space", | ||
* "spaceSize": 0, | ||
* "spaceUsedSize": 0, | ||
* "spaceAvailableSize": 0, | ||
* "physicalSpaceSize": 0 | ||
* } | ||
* ] | ||
* }, | ||
* "cost": 1574.14, | ||
* "afterGC": { | ||
* "heapStatistics": { | ||
* "totalHeapSize": 6053888, | ||
* "totalHeapSizeExecutable": 524288, | ||
* "totalPhysicalSize": 5500928, | ||
* "totalAvailableSize": 4341101384, | ||
* "totalGlobalHandlesSize": 8192, | ||
* "usedGlobalHandlesSize": 2112, | ||
* "usedHeapSize": 4059096, | ||
* "heapSizeLimit": 4345298944, | ||
* "mallocedMemory": 254128, | ||
* "externalMemory": 225138, | ||
* "peakMallocedMemory": 181760 | ||
* }, | ||
* "heapSpaceStatistics": [ | ||
* { | ||
* "spaceName": "read_only_space", | ||
* "spaceSize": 0, | ||
* "spaceUsedSize": 0, | ||
* "spaceAvailableSize": 0, | ||
* "physicalSpaceSize": 0 | ||
* } | ||
* ] | ||
* } | ||
* } | ||
* ], | ||
* "endTime": 1674059036865 | ||
* } | ||
* ``` | ||
* | ||
* Here's an example. | ||
* | ||
* ```js | ||
* const { GCProfiler } = require('v8'); | ||
* const profiler = new GCProfiler(); | ||
* profiler.start(); | ||
* setTimeout(() => { | ||
* console.log(profiler.stop()); | ||
* }, 1000); | ||
* ``` | ||
* @since v19.6.0, v18.15.0 | ||
*/ | ||
stop(): GCProfilerResult; | ||
} | ||
interface GCProfilerResult { | ||
version: number; | ||
startTime: number; | ||
endTime: number; | ||
statistics: Array<{ | ||
gcType: string; | ||
cost: number; | ||
beforeGC: { | ||
heapStatistics: HeapStatistics; | ||
heapSpaceStatistics: HeapSpaceStatistics[]; | ||
}; | ||
afterGC: { | ||
heapStatistics: HeapStatistics; | ||
heapSpaceStatistics: HeapSpaceStatistics[]; | ||
}; | ||
}>; | ||
} | ||
interface HeapStatistics { | ||
totalHeapSize: number; | ||
totalHeapSizeExecutable: number; | ||
totalPhysicalSize: number; | ||
totalAvailableSize: number; | ||
totalGlobalHandlesSize: number; | ||
usedGlobalHandlesSize: number; | ||
usedHeapSize: number; | ||
heapSizeLimit: number; | ||
mallocedMemory: number; | ||
externalMemory: number; | ||
peakMallocedMemory: number; | ||
} | ||
interface HeapSpaceStatistics { | ||
spaceName: string; | ||
spaceSize: number; | ||
spaceUsedSize: number; | ||
spaceAvailableSize: number; | ||
physicalSpaceSize: number; | ||
} | ||
/** | ||
* Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will | ||
* happen if a promise is created without ever getting a continuation. | ||
* @since v17.1.0, v16.14.0 | ||
* @param promise The promise being created. | ||
* @param parent The promise continued from, if applicable. | ||
*/ | ||
interface Init { | ||
(promise: Promise<unknown>, parent: Promise<unknown>): void; | ||
} | ||
/** | ||
* Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. | ||
* | ||
* The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. | ||
* The before callback may be called many times in the case where many continuations have been made from the same promise. | ||
* @since v17.1.0, v16.14.0 | ||
*/ | ||
interface Before { | ||
(promise: Promise<unknown>): void; | ||
} | ||
/** | ||
* Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. | ||
* @since v17.1.0, v16.14.0 | ||
*/ | ||
interface After { | ||
(promise: Promise<unknown>): void; | ||
} | ||
/** | ||
* Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or | ||
* {@link Promise.reject()}. | ||
* @since v17.1.0, v16.14.0 | ||
*/ | ||
interface Settled { | ||
(promise: Promise<unknown>): void; | ||
} | ||
/** | ||
* Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or | ||
* around an await, and when the promise resolves or rejects. | ||
* | ||
* Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and | ||
* `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. | ||
* @since v17.1.0, v16.14.0 | ||
*/ | ||
interface HookCallbacks { | ||
init?: Init; | ||
before?: Before; | ||
after?: After; | ||
settled?: Settled; | ||
} | ||
interface PromiseHooks { | ||
/** | ||
* The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. | ||
* @since v17.1.0, v16.14.0 | ||
* @param init The {@link Init | `init` callback} to call when a promise is created. | ||
* @return Call to stop the hook. | ||
*/ | ||
onInit: (init: Init) => Function; | ||
/** | ||
* The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. | ||
* @since v17.1.0, v16.14.0 | ||
* @param settled The {@link Settled | `settled` callback} to call when a promise is created. | ||
* @return Call to stop the hook. | ||
*/ | ||
onSettled: (settled: Settled) => Function; | ||
/** | ||
* The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. | ||
* @since v17.1.0, v16.14.0 | ||
* @param before The {@link Before | `before` callback} to call before a promise continuation executes. | ||
* @return Call to stop the hook. | ||
*/ | ||
onBefore: (before: Before) => Function; | ||
/** | ||
* The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. | ||
* @since v17.1.0, v16.14.0 | ||
* @param after The {@link After | `after` callback} to call after a promise continuation executes. | ||
* @return Call to stop the hook. | ||
*/ | ||
onAfter: (after: After) => Function; | ||
/** | ||
* Registers functions to be called for different lifetime events of each promise. | ||
* The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. | ||
* All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. | ||
* The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. | ||
* @since v17.1.0, v16.14.0 | ||
* @param callbacks The {@link HookCallbacks | Hook Callbacks} to register | ||
* @return Used for disabling hooks | ||
*/ | ||
createHook: (callbacks: HookCallbacks) => Function; | ||
} | ||
/** | ||
* The `promiseHooks` interface can be used to track promise lifecycle events. | ||
* @since v17.1.0, v16.14.0 | ||
*/ | ||
const promiseHooks: PromiseHooks; | ||
} | ||
declare module "node:v8" { | ||
export * from "v8"; | ||
} |
867
node/vm.d.ts
@@ -0,3 +1,42 @@ | ||
/** | ||
* The `node:vm` module enables compiling and running code within V8 Virtual | ||
* Machine contexts. | ||
* | ||
* **The `node:vm` module is not a security** | ||
* **mechanism. Do not use it to run untrusted code.** | ||
* | ||
* JavaScript code can be compiled and run immediately or | ||
* compiled, saved, and run later. | ||
* | ||
* A common use case is to run the code in a different V8 Context. This means | ||
* invoked code has a different global object than the invoking code. | ||
* | ||
* One can provide the context by `contextifying` an | ||
* object. The invoked code treats any property in the context like a | ||
* global variable. Any changes to global variables caused by the invoked | ||
* code are reflected in the context object. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* const x = 1; | ||
* | ||
* const context = { x: 2 }; | ||
* vm.createContext(context); // Contextify the object. | ||
* | ||
* const code = 'x += 40; var y = 17;'; | ||
* // `x` and `y` are global variables in the context. | ||
* // Initially, x has the value 2 because that is the value of context.x. | ||
* vm.runInContext(code, context); | ||
* | ||
* console.log(context.x); // 42 | ||
* console.log(context.y); // 17 | ||
* | ||
* console.log(x); // 1; y is not defined. | ||
* ``` | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/vm.js) | ||
*/ | ||
declare module "vm" { | ||
interface Context extends NodeJS.Dict<any> { } | ||
import { ImportAssertions } from "node:module"; | ||
interface Context extends NodeJS.Dict<any> {} | ||
interface BaseOptions { | ||
@@ -8,3 +47,3 @@ /** | ||
*/ | ||
filename?: string; | ||
filename?: string | undefined; | ||
/** | ||
@@ -14,14 +53,23 @@ * Specifies the line number offset that is displayed in stack traces produced by this script. | ||
*/ | ||
lineOffset?: number; | ||
lineOffset?: number | undefined; | ||
/** | ||
* Specifies the column number offset that is displayed in stack traces produced by this script. | ||
* Default: `0` | ||
* @default 0 | ||
*/ | ||
columnOffset?: number; | ||
columnOffset?: number | undefined; | ||
} | ||
interface ScriptOptions extends BaseOptions { | ||
displayErrors?: boolean; | ||
timeout?: number; | ||
cachedData?: Buffer; | ||
produceCachedData?: boolean; | ||
/** | ||
* V8's code cache data for the supplied source. | ||
*/ | ||
cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; | ||
/** @deprecated in favor of `script.createCachedData()` */ | ||
produceCachedData?: boolean | undefined; | ||
/** | ||
* Called during evaluation of this module when `import()` is called. | ||
* If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. | ||
*/ | ||
importModuleDynamically?: | ||
| ((specifier: string, script: Script, importAssertions: ImportAssertions) => Module) | ||
| undefined; | ||
} | ||
@@ -33,3 +81,3 @@ interface RunningScriptOptions extends BaseOptions { | ||
*/ | ||
displayErrors?: boolean; | ||
displayErrors?: boolean | undefined; | ||
/** | ||
@@ -39,3 +87,3 @@ * Specifies the number of milliseconds to execute code before terminating execution. | ||
*/ | ||
timeout?: number; | ||
timeout?: number | undefined; | ||
/** | ||
@@ -47,8 +95,29 @@ * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. | ||
*/ | ||
breakOnSigint?: boolean; | ||
breakOnSigint?: boolean | undefined; | ||
} | ||
interface RunningScriptInNewContextOptions extends RunningScriptOptions { | ||
/** | ||
* Human-readable name of the newly created context. | ||
*/ | ||
contextName?: CreateContextOptions["name"]; | ||
/** | ||
* Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, | ||
* but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. | ||
* Most notably, this string should omit the trailing slash, as that denotes a path. | ||
*/ | ||
contextOrigin?: CreateContextOptions["origin"]; | ||
contextCodeGeneration?: CreateContextOptions["codeGeneration"]; | ||
/** | ||
* If set to `afterEvaluate`, microtasks will be run immediately after the script has run. | ||
*/ | ||
microtaskMode?: 'afterEvaluate'; | ||
microtaskMode?: CreateContextOptions["microtaskMode"]; | ||
} | ||
interface RunningCodeOptions extends RunningScriptOptions { | ||
cachedData?: ScriptOptions["cachedData"]; | ||
importModuleDynamically?: ScriptOptions["importModuleDynamically"]; | ||
} | ||
interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { | ||
cachedData?: ScriptOptions["cachedData"]; | ||
importModuleDynamically?: ScriptOptions["importModuleDynamically"]; | ||
} | ||
interface CompileFunctionOptions extends BaseOptions { | ||
@@ -58,3 +127,3 @@ /** | ||
*/ | ||
cachedData?: Buffer; | ||
cachedData?: Buffer | undefined; | ||
/** | ||
@@ -64,14 +133,12 @@ * Specifies whether to produce new cache data. | ||
*/ | ||
produceCachedData?: boolean; | ||
produceCachedData?: boolean | undefined; | ||
/** | ||
* The sandbox/context in which the said function should be compiled in. | ||
*/ | ||
parsingContext?: Context; | ||
parsingContext?: Context | undefined; | ||
/** | ||
* An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling | ||
*/ | ||
contextExtensions?: Object[]; | ||
contextExtensions?: Object[] | undefined; | ||
} | ||
interface CreateContextOptions { | ||
@@ -82,3 +149,3 @@ /** | ||
*/ | ||
name?: string; | ||
name?: string | undefined; | ||
/** | ||
@@ -91,20 +158,24 @@ * Corresponds to the newly created context for display purposes. | ||
*/ | ||
origin?: string; | ||
codeGeneration?: { | ||
/** | ||
* If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) | ||
* will throw an EvalError. | ||
* @default true | ||
*/ | ||
strings?: boolean; | ||
/** | ||
* If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. | ||
* @default true | ||
*/ | ||
wasm?: boolean; | ||
}; | ||
origin?: string | undefined; | ||
codeGeneration?: | ||
| { | ||
/** | ||
* If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) | ||
* will throw an EvalError. | ||
* @default true | ||
*/ | ||
strings?: boolean | undefined; | ||
/** | ||
* If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. | ||
* @default true | ||
*/ | ||
wasm?: boolean | undefined; | ||
} | ||
| undefined; | ||
/** | ||
* If set to `afterEvaluate`, microtasks will be run immediately after the script has run. | ||
*/ | ||
microtaskMode?: "afterEvaluate" | undefined; | ||
} | ||
type MeasureMemoryMode = 'summary' | 'detailed'; | ||
type MeasureMemoryMode = "summary" | "detailed"; | ||
interface MeasureMemoryOptions { | ||
@@ -114,6 +185,8 @@ /** | ||
*/ | ||
mode?: MeasureMemoryMode; | ||
context?: Context; | ||
mode?: MeasureMemoryMode | undefined; | ||
/** | ||
* @default 'default' | ||
*/ | ||
execution?: "default" | "eager" | undefined; | ||
} | ||
interface MemoryMeasurement { | ||
@@ -125,33 +198,715 @@ total: { | ||
} | ||
/** | ||
* Instances of the `vm.Script` class contain precompiled scripts that can be | ||
* executed in specific contexts. | ||
* @since v0.3.1 | ||
*/ | ||
class Script { | ||
constructor(code: string, options?: ScriptOptions); | ||
runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; | ||
runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; | ||
constructor(code: string, options?: ScriptOptions | string); | ||
/** | ||
* Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access | ||
* to local scope. | ||
* | ||
* The following example compiles code that increments a global variable, sets | ||
* the value of another global variable, then execute the code multiple times. | ||
* The globals are contained in the `context` object. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* const context = { | ||
* animal: 'cat', | ||
* count: 2, | ||
* }; | ||
* | ||
* const script = new vm.Script('count += 1; name = "kitty";'); | ||
* | ||
* vm.createContext(context); | ||
* for (let i = 0; i < 10; ++i) { | ||
* script.runInContext(context); | ||
* } | ||
* | ||
* console.log(context); | ||
* // Prints: { animal: 'cat', count: 12, name: 'kitty' } | ||
* ``` | ||
* | ||
* Using the `timeout` or `breakOnSigint` options will result in new event loops | ||
* and corresponding threads being started, which have a non-zero performance | ||
* overhead. | ||
* @since v0.3.1 | ||
* @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. | ||
* @return the result of the very last statement executed in the script. | ||
*/ | ||
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. | ||
* | ||
* 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 | ||
* contained within each individual `context`. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* const script = new vm.Script('globalVar = "set"'); | ||
* | ||
* const contexts = [{}, {}, {}]; | ||
* contexts.forEach((context) => { | ||
* script.runInNewContext(context); | ||
* }); | ||
* | ||
* console.log(contexts); | ||
* // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] | ||
* ``` | ||
* @since v0.3.1 | ||
* @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. | ||
* @return the result of the very last statement executed in the script. | ||
*/ | ||
runInNewContext(contextObject?: Context, 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. | ||
* | ||
* The following example compiles code that increments a `global` variable then | ||
* executes that code multiple times: | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* global.globalVar = 0; | ||
* | ||
* const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); | ||
* | ||
* for (let i = 0; i < 1000; ++i) { | ||
* script.runInThisContext(); | ||
* } | ||
* | ||
* console.log(globalVar); | ||
* | ||
* // 1000 | ||
* ``` | ||
* @since v0.3.1 | ||
* @return the result of the very last statement executed in the script. | ||
*/ | ||
runInThisContext(options?: RunningScriptOptions): any; | ||
/** | ||
* Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any | ||
* time and any number of times. | ||
* | ||
* The code cache of the `Script` doesn't contain any JavaScript observable | ||
* states. The code cache is safe to be saved along side the script source and | ||
* used to construct new `Script` instances multiple times. | ||
* | ||
* Functions in the `Script` source can be marked as lazily compiled and they are | ||
* not compiled at construction of the `Script`. These functions are going to be | ||
* compiled when they are invoked the first time. The code cache serializes the | ||
* metadata that V8 currently knows about the `Script` that it can use to speed up | ||
* future compilations. | ||
* | ||
* ```js | ||
* const script = new vm.Script(` | ||
* function add(a, b) { | ||
* return a + b; | ||
* } | ||
* | ||
* const x = add(1, 2); | ||
* `); | ||
* | ||
* const cacheWithoutAdd = script.createCachedData(); | ||
* // In `cacheWithoutAdd` the function `add()` is marked for full compilation | ||
* // upon invocation. | ||
* | ||
* script.runInThisContext(); | ||
* | ||
* const cacheWithAdd = script.createCachedData(); | ||
* // `cacheWithAdd` contains fully compiled function `add()`. | ||
* ``` | ||
* @since v10.6.0 | ||
*/ | ||
createCachedData(): Buffer; | ||
/** @deprecated in favor of `script.createCachedData()` */ | ||
cachedDataProduced?: boolean | undefined; | ||
/** | ||
* When `cachedData` is supplied to create the `vm.Script`, this value will be set | ||
* to either `true` or `false` depending on acceptance of the data by V8\. | ||
* Otherwise the value is `undefined`. | ||
* @since v5.7.0 | ||
*/ | ||
cachedDataRejected?: boolean | undefined; | ||
cachedData?: Buffer | undefined; | ||
/** | ||
* When the script is compiled from a source that contains a source map magic | ||
* comment, this property will be set to the URL of the source map. | ||
* | ||
* ```js | ||
* import vm from 'node:vm'; | ||
* | ||
* const script = new vm.Script(` | ||
* function myFunc() {} | ||
* //# sourceMappingURL=sourcemap.json | ||
* `); | ||
* | ||
* console.log(script.sourceMapURL); | ||
* // Prints: sourcemap.json | ||
* ``` | ||
* @since v19.1.0, v18.13.0 | ||
*/ | ||
sourceMapURL?: string | undefined; | ||
} | ||
/** | ||
* If given a `contextObject`, the `vm.createContext()` method will `prepare | ||
* that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. 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 variables | ||
* will remain unchanged. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* global.globalVar = 3; | ||
* | ||
* const context = { globalVar: 1 }; | ||
* vm.createContext(context); | ||
* | ||
* vm.runInContext('globalVar *= 2;', context); | ||
* | ||
* console.log(context); | ||
* // Prints: { globalVar: 2 } | ||
* | ||
* console.log(global.globalVar); | ||
* // Prints: 3 | ||
* ``` | ||
* | ||
* If `contextObject` is omitted (or passed explicitly as `undefined`), a new, | ||
* empty `contextified` object will be returned. | ||
* | ||
* 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 | ||
* web browser, the method can be used to create a single context representing a | ||
* window's global object, then run all `<script>` tags together within that | ||
* context. | ||
* | ||
* The provided `name` and `origin` of the context are made visible through the | ||
* Inspector API. | ||
* @since v0.3.1 | ||
* @return contextified object. | ||
*/ | ||
function createContext(sandbox?: Context, options?: CreateContextOptions): Context; | ||
/** | ||
* Returns `true` if the given `object` object has been `contextified` using {@link createContext}. | ||
* @since v0.11.7 | ||
*/ | ||
function isContext(sandbox: Context): boolean; | ||
function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; | ||
function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; | ||
function runInThisContext(code: string, options?: RunningScriptOptions | string): any; | ||
function compileFunction(code: string, params?: ReadonlyArray<string>, options?: CompileFunctionOptions): Function; | ||
/** | ||
* Measure the memory known to V8 and used by the current execution context or a specified context. | ||
* The `vm.runInContext()` method compiles `code`, runs it within the context of | ||
* the `contextifiedObject`, then returns the result. Running code does not have | ||
* access to the local scope. The `contextifiedObject` object _must_ have been | ||
* previously `contextified` using the {@link createContext} method. | ||
* | ||
* If `options` is a string, then it specifies the filename. | ||
* | ||
* The following example compiles and executes different scripts using a single `contextified` object: | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* const contextObject = { globalVar: 1 }; | ||
* vm.createContext(contextObject); | ||
* | ||
* for (let i = 0; i < 10; ++i) { | ||
* vm.runInContext('globalVar *= 2;', contextObject); | ||
* } | ||
* console.log(contextObject); | ||
* // Prints: { globalVar: 1024 } | ||
* ``` | ||
* @since v0.3.1 | ||
* @param code The JavaScript code to compile and run. | ||
* @param contextifiedObject The `contextified` object that will be used as the `global` when the `code` is compiled and run. | ||
* @return the result of the very last statement executed in the script. | ||
*/ | ||
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. | ||
* | ||
* If `options` is a string, then it specifies the filename. | ||
* | ||
* The following example compiles and executes code that increments a global | ||
* variable and sets a new one. These globals are contained in the `contextObject`. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* const contextObject = { | ||
* animal: 'cat', | ||
* count: 2, | ||
* }; | ||
* | ||
* vm.runInNewContext('count += 1; name = "kitty"', contextObject); | ||
* console.log(contextObject); | ||
* // Prints: { animal: 'cat', count: 3, name: 'kitty' } | ||
* ``` | ||
* @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. | ||
* @return the result of the very last statement executed in the script. | ||
*/ | ||
function runInNewContext( | ||
code: string, | ||
contextObject?: Context, | ||
options?: RunningCodeInNewContextOptions | string, | ||
): any; | ||
/** | ||
* `vm.runInThisContext()` compiles `code`, runs it within the context of the | ||
* current `global` and returns the result. Running code does not have access to | ||
* local scope, but does have access to the current `global` object. | ||
* | ||
* If `options` is a string, then it specifies the filename. | ||
* | ||
* The following example illustrates using both `vm.runInThisContext()` and | ||
* 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'); | ||
* let localVar = 'initial value'; | ||
* | ||
* const vmResult = vm.runInThisContext('localVar = "vm";'); | ||
* console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`); | ||
* // Prints: vmResult: 'vm', localVar: 'initial value' | ||
* | ||
* const evalResult = eval('localVar = "eval";'); | ||
* console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`); | ||
* // Prints: evalResult: 'eval', localVar: 'eval' | ||
* ``` | ||
* | ||
* Because `vm.runInThisContext()` does not have access to the local scope,`localVar` is unchanged. In contrast, | ||
* [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) _does_ have access to the | ||
* local scope, so the value `localVar` is changed. In this way`vm.runInThisContext()` is much like an [indirect `eval()` call](https://es5.github.io/#x10.4.2), e.g.`(0,eval)('code')`. | ||
* | ||
* ## Example: Running an HTTP server within a VM | ||
* | ||
* When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global | ||
* context. The code passed to this VM context will have its own isolated scope. | ||
* | ||
* In order to run a simple web server using the `node:http` module the code passed | ||
* to the context must either call `require('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'); | ||
* | ||
* const code = ` | ||
* ((require) => { | ||
* const http = require('node:http'); | ||
* | ||
* http.createServer((request, response) => { | ||
* response.writeHead(200, { 'Content-Type': 'text/plain' }); | ||
* response.end('Hello World\\n'); | ||
* }).listen(8124); | ||
* | ||
* console.log('Server running at http://127.0.0.1:8124/'); | ||
* })`; | ||
* | ||
* vm.runInThisContext(code)(require); | ||
* ``` | ||
* | ||
* The `require()` in the above case shares the state with the context it is | ||
* passed from. This may introduce risks when untrusted code is executed, e.g. | ||
* altering objects in the context in unwanted ways. | ||
* @since v0.3.1 | ||
* @param code The JavaScript code to compile and run. | ||
* @return the result of the very last statement executed in the script. | ||
*/ | ||
function runInThisContext(code: string, options?: RunningCodeOptions | string): any; | ||
/** | ||
* Compiles the given code into the provided context (if no context is | ||
* supplied, the current context is used), and returns it wrapped inside a | ||
* function with the given `params`. | ||
* @since v10.10.0 | ||
* @param code The body of the function to compile. | ||
* @param params An array of strings containing all parameters for the function. | ||
*/ | ||
function compileFunction( | ||
code: string, | ||
params?: readonly string[], | ||
options?: CompileFunctionOptions, | ||
): Function & { | ||
cachedData?: Script["cachedData"] | undefined; | ||
cachedDataProduced?: Script["cachedDataProduced"] | undefined; | ||
cachedDataRejected?: Script["cachedDataRejected"] | undefined; | ||
}; | ||
/** | ||
* Measure the memory known to V8 and used by all contexts known to the | ||
* current V8 isolate, or the main context. | ||
* | ||
* The format of the object that the returned Promise may resolve with is | ||
* specific to the V8 engine and may change from one version of V8 to the next. | ||
* | ||
* The returned result is different from the statistics returned by | ||
* `v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measures | ||
* the memory reachable by V8 from a specific context, while | ||
* `v8.getHeapSpaceStatistics()` measures the memory used by an instance | ||
* of V8 engine, which can switch among multiple contexts that reference | ||
* objects in the heap of one engine. | ||
* The returned result is different from the statistics returned by`v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measure the | ||
* memory reachable by each V8 specific contexts in the current instance of | ||
* the V8 engine, while the result of `v8.getHeapSpaceStatistics()` measure | ||
* the memory occupied by each heap space in the current V8 instance. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* // Measure the memory used by the main context. | ||
* vm.measureMemory({ mode: 'summary' }) | ||
* // This is the same as vm.measureMemory() | ||
* .then((result) => { | ||
* // The current format is: | ||
* // { | ||
* // total: { | ||
* // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ] | ||
* // } | ||
* // } | ||
* console.log(result); | ||
* }); | ||
* | ||
* const context = vm.createContext({ a: 1 }); | ||
* vm.measureMemory({ mode: 'detailed', execution: 'eager' }) | ||
* .then((result) => { | ||
* // Reference the context here so that it won't be GC'ed | ||
* // until the measurement is complete. | ||
* console.log(context.a); | ||
* // { | ||
* // total: { | ||
* // jsMemoryEstimate: 2574732, | ||
* // jsMemoryRange: [ 2574732, 2904372 ] | ||
* // }, | ||
* // current: { | ||
* // jsMemoryEstimate: 2438996, | ||
* // jsMemoryRange: [ 2438996, 2768636 ] | ||
* // }, | ||
* // other: [ | ||
* // { | ||
* // jsMemoryEstimate: 135736, | ||
* // jsMemoryRange: [ 135736, 465376 ] | ||
* // } | ||
* // ] | ||
* // } | ||
* console.log(result); | ||
* }); | ||
* ``` | ||
* @since v13.10.0 | ||
* @experimental | ||
*/ | ||
function measureMemory(options?: MeasureMemoryOptions): Promise<MemoryMeasurement>; | ||
interface ModuleEvaluateOptions { | ||
timeout?: RunningScriptOptions["timeout"] | undefined; | ||
breakOnSigint?: RunningScriptOptions["breakOnSigint"] | undefined; | ||
} | ||
type ModuleLinker = ( | ||
specifier: string, | ||
referencingModule: Module, | ||
extra: { | ||
assert: Object; | ||
}, | ||
) => Module | Promise<Module>; | ||
type ModuleStatus = "unlinked" | "linking" | "linked" | "evaluating" | "evaluated" | "errored"; | ||
/** | ||
* This feature is only available with the `--experimental-vm-modules` command | ||
* flag enabled. | ||
* | ||
* The `vm.Module` class provides a low-level interface for using | ||
* ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script`class that closely mirrors [Module Record](https://www.ecma-international.org/ecma-262/#sec-abstract-module-records) | ||
* s as defined in the ECMAScript | ||
* specification. | ||
* | ||
* Unlike `vm.Script` however, every `vm.Module` object is bound to a context from | ||
* its creation. Operations on `vm.Module` objects are intrinsically asynchronous, | ||
* in contrast with the synchronous nature of `vm.Script` objects. The use of | ||
* 'async' functions can help with manipulating `vm.Module` objects. | ||
* | ||
* Using a `vm.Module` object requires three distinct steps: creation/parsing, | ||
* linking, and evaluation. These three steps are illustrated in the following | ||
* example. | ||
* | ||
* This implementation lies at a lower level than the `ECMAScript Module | ||
* loader`. There is also no way to interact with the Loader yet, though | ||
* support is planned. | ||
* | ||
* ```js | ||
* import vm from 'node:vm'; | ||
* | ||
* const contextifiedObject = vm.createContext({ | ||
* secret: 42, | ||
* print: console.log, | ||
* }); | ||
* | ||
* // Step 1 | ||
* // | ||
* // Create a Module by constructing a new `vm.SourceTextModule` object. This | ||
* // parses the provided source text, throwing a `SyntaxError` if anything goes | ||
* // wrong. By default, a Module is created in the top context. But here, we | ||
* // specify `contextifiedObject` as the context this Module belongs to. | ||
* // | ||
* // Here, we attempt to obtain the default export from the module "foo", and | ||
* // put it into local binding "secret". | ||
* | ||
* const bar = new vm.SourceTextModule(` | ||
* import s from 'foo'; | ||
* s; | ||
* print(s); | ||
* `, { context: contextifiedObject }); | ||
* | ||
* // Step 2 | ||
* // | ||
* // "Link" the imported dependencies of this Module to it. | ||
* // | ||
* // The provided linking callback (the "linker") accepts two arguments: the | ||
* // parent module (`bar` in this case) and the string that is the specifier of | ||
* // the imported module. The callback is expected to return a Module that | ||
* // corresponds to the provided specifier, with certain requirements documented | ||
* // in `module.link()`. | ||
* // | ||
* // If linking has not started for the returned Module, the same linker | ||
* // callback will be called on the returned Module. | ||
* // | ||
* // Even top-level Modules without dependencies must be explicitly linked. The | ||
* // callback provided would never be called, however. | ||
* // | ||
* // The link() method returns a Promise that will be resolved when all the | ||
* // Promises returned by the linker resolve. | ||
* // | ||
* // Note: This is a contrived example in that the linker function creates a new | ||
* // "foo" module every time it is called. In a full-fledged module system, a | ||
* // cache would probably be used to avoid duplicated modules. | ||
* | ||
* async function linker(specifier, referencingModule) { | ||
* if (specifier === 'foo') { | ||
* return new vm.SourceTextModule(` | ||
* // The "secret" variable refers to the global variable we added to | ||
* // "contextifiedObject" when creating the context. | ||
* export default secret; | ||
* `, { context: referencingModule.context }); | ||
* | ||
* // Using `contextifiedObject` instead of `referencingModule.context` | ||
* // here would work as well. | ||
* } | ||
* throw new Error(`Unable to resolve dependency: ${specifier}`); | ||
* } | ||
* await bar.link(linker); | ||
* | ||
* // Step 3 | ||
* // | ||
* // Evaluate the Module. The evaluate() method returns a promise which will | ||
* // resolve after the module has finished evaluating. | ||
* | ||
* // Prints 42. | ||
* await bar.evaluate(); | ||
* ``` | ||
* @since v13.0.0, v12.16.0 | ||
* @experimental | ||
*/ | ||
class Module { | ||
/** | ||
* The specifiers of all dependencies of this module. The returned array is frozen | ||
* to disallow any changes to it. | ||
* | ||
* Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in | ||
* the ECMAScript specification. | ||
*/ | ||
dependencySpecifiers: readonly string[]; | ||
/** | ||
* If the `module.status` is `'errored'`, this property contains the exception | ||
* thrown by the module during evaluation. If the status is anything else, | ||
* accessing this property will result in a thrown exception. | ||
* | ||
* The value `undefined` cannot be used for cases where there is not a thrown | ||
* exception due to possible ambiguity with `throw undefined;`. | ||
* | ||
* Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s | ||
* in the ECMAScript specification. | ||
*/ | ||
error: any; | ||
/** | ||
* The identifier of the current module, as set in the constructor. | ||
*/ | ||
identifier: string; | ||
context: Context; | ||
/** | ||
* The namespace object of the module. This is only available after linking | ||
* (`module.link()`) has completed. | ||
* | ||
* Corresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript | ||
* specification. | ||
*/ | ||
namespace: Object; | ||
/** | ||
* The current status of the module. Will be one of: | ||
* | ||
* * `'unlinked'`: `module.link()` has not yet been called. | ||
* * `'linking'`: `module.link()` has been called, but not all Promises returned | ||
* by the linker function have been resolved yet. | ||
* * `'linked'`: The module has been linked successfully, and all of its | ||
* dependencies are linked, but `module.evaluate()` has not yet been called. | ||
* * `'evaluating'`: The module is being evaluated through a `module.evaluate()` on | ||
* itself or a parent module. | ||
* * `'evaluated'`: The module has been successfully evaluated. | ||
* * `'errored'`: The module has been evaluated, but an exception was thrown. | ||
* | ||
* Other than `'errored'`, this status string corresponds to the specification's [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)'s `[[Status]]` field. `'errored'` | ||
* corresponds to`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a | ||
* value that is not `undefined`. | ||
*/ | ||
status: ModuleStatus; | ||
/** | ||
* Evaluate the module. | ||
* | ||
* This must be called after the module has been linked; otherwise it will reject. | ||
* It could be called also when the module has already been evaluated, in which | ||
* case it will either do nothing if the initial evaluation ended in success | ||
* (`module.status` is `'evaluated'`) or it will re-throw the exception that the | ||
* initial evaluation resulted in (`module.status` is `'errored'`). | ||
* | ||
* This method cannot be called while the module is being evaluated | ||
* (`module.status` is `'evaluating'`). | ||
* | ||
* Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in the | ||
* ECMAScript specification. | ||
* @return Fulfills with `undefined` upon success. | ||
*/ | ||
evaluate(options?: ModuleEvaluateOptions): Promise<void>; | ||
/** | ||
* Link module dependencies. This method must be called before evaluation, and | ||
* can only be called once per module. | ||
* | ||
* The function is expected to return a `Module` object or a `Promise` that | ||
* eventually resolves to a `Module` object. The returned `Module` must satisfy the | ||
* following two invariants: | ||
* | ||
* * It must belong to the same context as the parent `Module`. | ||
* * Its `status` must not be `'errored'`. | ||
* | ||
* If the returned `Module`'s `status` is `'unlinked'`, this method will be | ||
* recursively called on the returned `Module` with the same provided `linker`function. | ||
* | ||
* `link()` returns a `Promise` that will either get resolved when all linking | ||
* instances resolve to a valid `Module`, or rejected if the linker function either | ||
* throws an exception or returns an invalid `Module`. | ||
* | ||
* The linker function roughly corresponds to the implementation-defined [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the | ||
* ECMAScript | ||
* specification, with a few key differences: | ||
* | ||
* * The linker function is allowed to be asynchronous while [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous. | ||
* | ||
* The actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation used during module | ||
* linking is one that returns the modules linked during linking. Since at | ||
* that point all modules would have been fully linked already, the [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per | ||
* specification. | ||
* | ||
* Corresponds to the [Link() concrete method](https://tc39.es/ecma262/#sec-moduledeclarationlinking) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in | ||
* the ECMAScript specification. | ||
*/ | ||
link(linker: ModuleLinker): Promise<void>; | ||
} | ||
interface SourceTextModuleOptions { | ||
/** | ||
* String used in stack traces. | ||
* @default 'vm:module(i)' where i is a context-specific ascending index. | ||
*/ | ||
identifier?: string | undefined; | ||
cachedData?: ScriptOptions["cachedData"] | undefined; | ||
context?: Context | undefined; | ||
lineOffset?: BaseOptions["lineOffset"] | undefined; | ||
columnOffset?: BaseOptions["columnOffset"] | undefined; | ||
/** | ||
* Called during evaluation of this module to initialize the `import.meta`. | ||
*/ | ||
initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined; | ||
importModuleDynamically?: ScriptOptions["importModuleDynamically"] | undefined; | ||
} | ||
/** | ||
* This feature is only available with the `--experimental-vm-modules` command | ||
* flag enabled. | ||
* | ||
* The `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as | ||
* defined in the ECMAScript specification. | ||
* @since v9.6.0 | ||
* @experimental | ||
*/ | ||
class SourceTextModule extends Module { | ||
/** | ||
* Creates a new `SourceTextModule` instance. | ||
* @param code JavaScript Module code to parse | ||
*/ | ||
constructor(code: string, options?: SourceTextModuleOptions); | ||
} | ||
interface SyntheticModuleOptions { | ||
/** | ||
* String used in stack traces. | ||
* @default 'vm:module(i)' where i is a context-specific ascending index. | ||
*/ | ||
identifier?: string | undefined; | ||
/** | ||
* The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in. | ||
*/ | ||
context?: Context | undefined; | ||
} | ||
/** | ||
* This feature is only available with the `--experimental-vm-modules` command | ||
* flag enabled. | ||
* | ||
* The `vm.SyntheticModule` class provides the [Synthetic Module Record](https://heycam.github.io/webidl/#synthetic-module-records) as | ||
* defined in the WebIDL specification. The purpose of synthetic modules is to | ||
* provide a generic interface for exposing non-JavaScript sources to ECMAScript | ||
* module graphs. | ||
* | ||
* ```js | ||
* const vm = require('node:vm'); | ||
* | ||
* const source = '{ "a": 1 }'; | ||
* const module = new vm.SyntheticModule(['default'], function() { | ||
* const obj = JSON.parse(source); | ||
* this.setExport('default', obj); | ||
* }); | ||
* | ||
* // Use `module` in linking... | ||
* ``` | ||
* @since v13.0.0, v12.16.0 | ||
* @experimental | ||
*/ | ||
class SyntheticModule extends Module { | ||
/** | ||
* Creates a new `SyntheticModule` instance. | ||
* @param exportNames Array of names that will be exported from the module. | ||
* @param evaluateCallback Called when the module is evaluated. | ||
*/ | ||
constructor( | ||
exportNames: string[], | ||
evaluateCallback: (this: SyntheticModule) => void, | ||
options?: SyntheticModuleOptions, | ||
); | ||
/** | ||
* This method is used after the module is linked to set the values of exports. If | ||
* it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error | ||
* will be thrown. | ||
* | ||
* ```js | ||
* import vm from 'node:vm'; | ||
* | ||
* const m = new vm.SyntheticModule(['x'], () => { | ||
* m.setExport('x', 1); | ||
* }); | ||
* | ||
* await m.link(() => {}); | ||
* await m.evaluate(); | ||
* | ||
* assert.strictEqual(m.namespace.x, 1); | ||
* ``` | ||
* @since v13.0.0, v12.16.0 | ||
* @param name Name of the export to set. | ||
* @param value The value to set the export to. | ||
*/ | ||
setExport(name: string, value: any): void; | ||
} | ||
} | ||
declare module "node:vm" { | ||
export * from "vm"; | ||
} |
@@ -1,2 +0,68 @@ | ||
declare module 'wasi' { | ||
/** | ||
* The WASI API provides an implementation of the [WebAssembly System Interface](https://wasi.dev/) specification. WASI gives sandboxed WebAssembly applications access to the | ||
* underlying operating system via a collection of POSIX-like functions. | ||
* | ||
* ```js | ||
* import { readFile } from 'node:fs/promises'; | ||
* import { WASI } from 'wasi'; | ||
* import { argv, env } from 'node:process'; | ||
* | ||
* const wasi = new WASI({ | ||
* version: 'preview1', | ||
* args: argv, | ||
* env, | ||
* preopens: { | ||
* '/sandbox': '/some/real/path/that/wasm/can/access', | ||
* }, | ||
* }); | ||
* | ||
* const wasm = await WebAssembly.compile( | ||
* await readFile(new URL('./demo.wasm', import.meta.url)), | ||
* ); | ||
* const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject()); | ||
* | ||
* wasi.start(instance); | ||
* ``` | ||
* | ||
* To run the above example, create a new WebAssembly text format file named`demo.wat`: | ||
* | ||
* ```text | ||
* (module | ||
* ;; Import the required fd_write WASI function which will write the given io vectors to stdout | ||
* ;; The function signature for fd_write is: | ||
* ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written | ||
* (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32))) | ||
* | ||
* (memory 1) | ||
* (export "memory" (memory 0)) | ||
* | ||
* ;; Write 'hello world\n' to memory at an offset of 8 bytes | ||
* ;; Note the trailing newline which is required for the text to appear | ||
* (data (i32.const 8) "hello world\n") | ||
* | ||
* (func $main (export "_start") | ||
* ;; Creating a new io vector within linear memory | ||
* (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string | ||
* (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string | ||
* | ||
* (call $fd_write | ||
* (i32.const 1) ;; file_descriptor - 1 for stdout | ||
* (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0 | ||
* (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one. | ||
* (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written | ||
* ) | ||
* drop ;; Discard the number of bytes written from the top of the stack | ||
* ) | ||
* ) | ||
* ``` | ||
* | ||
* Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm` | ||
* | ||
* ```bash | ||
* wat2wasm demo.wat | ||
* ``` | ||
* @experimental | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/wasi.js) | ||
*/ | ||
declare module "wasi" { | ||
interface WASIOptions { | ||
@@ -8,4 +74,3 @@ /** | ||
*/ | ||
args?: string[]; | ||
args?: string[] | undefined; | ||
/** | ||
@@ -15,4 +80,3 @@ * An object similar to `process.env` that the WebAssembly | ||
*/ | ||
env?: object; | ||
env?: object | undefined; | ||
/** | ||
@@ -24,13 +88,11 @@ * This object represents the WebAssembly application's | ||
*/ | ||
preopens?: NodeJS.Dict<string>; | ||
preopens?: NodeJS.Dict<string> | undefined; | ||
/** | ||
* By default, WASI applications terminate the Node.js | ||
* process via the `__wasi_proc_exit()` function. Setting this option to `true` | ||
* causes `wasi.start()` to return the exit code rather than terminate the | ||
* process. | ||
* @default false | ||
* By default, when WASI applications call `__wasi_proc_exit()` | ||
* `wasi.start()` will return with the exit code specified rather than terminatng the process. | ||
* Setting this option to `false` will cause the Node.js process to exit with | ||
* the specified exit code instead. | ||
* @default true | ||
*/ | ||
returnOnExit?: boolean; | ||
returnOnExit?: boolean | undefined; | ||
/** | ||
@@ -40,4 +102,3 @@ * The file descriptor used as standard input in the WebAssembly application. | ||
*/ | ||
stdin?: number; | ||
stdin?: number | undefined; | ||
/** | ||
@@ -47,4 +108,3 @@ * The file descriptor used as standard output in the WebAssembly application. | ||
*/ | ||
stdout?: number; | ||
stdout?: number | undefined; | ||
/** | ||
@@ -54,36 +114,45 @@ * The file descriptor used as standard error in the WebAssembly application. | ||
*/ | ||
stderr?: number; | ||
stderr?: number | undefined; | ||
/** | ||
* The version of WASI requested. | ||
* Currently the only supported versions are `'unstable'` and `'preview1'`. | ||
* @since v20.0.0 | ||
*/ | ||
version: string; | ||
} | ||
/** | ||
* The `WASI` class provides the WASI system call API and additional convenience | ||
* methods for working with WASI-based applications. Each `WASI` instance | ||
* represents a distinct sandbox environment. For security purposes, each `WASI`instance must have its command-line arguments, environment variables, and | ||
* sandbox directory structure configured explicitly. | ||
* @since v13.3.0, v12.16.0 | ||
*/ | ||
class WASI { | ||
constructor(options?: WASIOptions); | ||
/** | ||
* Attempt to begin execution of `instance` as a WASI command by invoking its`_start()` export. If `instance` does not contain a `_start()` export, or if`instance` contains an `_initialize()` | ||
* export, then an exception is thrown. | ||
* | ||
* Attempt to begin execution of `instance` by invoking its `_start()` export. | ||
* If `instance` does not contain a `_start()` export, then `start()` attempts to | ||
* invoke the `__wasi_unstable_reactor_start()` export. If neither of those exports | ||
* is present on `instance`, then `start()` does nothing. | ||
* `start()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`. If | ||
* `instance` does not have a `memory` export an exception is thrown. | ||
* | ||
* `start()` requires that `instance` exports a [`WebAssembly.Memory`][] named | ||
* `memory`. If `instance` does not have a `memory` export an exception is thrown. | ||
* | ||
* If `start()` is called more than once, an exception is thrown. | ||
* @since v13.3.0, v12.16.0 | ||
*/ | ||
start(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. | ||
start(instance: object): number; // TODO: avoid DOM dependency until WASM moved to own lib. | ||
/** | ||
* Attempt to initialize `instance` as a WASI reactor by invoking its `_initialize()` export, if it is present. | ||
* If `instance` contains a `_start()` export, then an exception is thrown. | ||
* Attempt to initialize `instance` as a WASI reactor by invoking its`_initialize()` export, if it is present. If `instance` contains a `_start()`export, then an exception is thrown. | ||
* | ||
* `start()` requires that `instance` exports a [`WebAssembly.Memory`][] named | ||
* `memory`. If `instance` does not have a `memory` export an exception is thrown. | ||
* `initialize()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`. | ||
* If `instance` does not have a `memory` export an exception is thrown. | ||
* | ||
* If `initialize()` is called more than once, an exception is thrown. | ||
* @since v14.6.0, v12.19.0 | ||
*/ | ||
initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. | ||
/** | ||
* Is an object that implements the WASI system call API. This object | ||
* should be passed as the `wasi_snapshot_preview1` import during the instantiation of a | ||
* [`WebAssembly.Instance`][]. | ||
* `wasiImport` is an object that implements the WASI system call API. This object | ||
* should be passed as the `wasi_snapshot_preview1` import during the instantiation | ||
* of a [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance). | ||
* @since v13.3.0, v12.16.0 | ||
*/ | ||
@@ -93,1 +162,4 @@ readonly wasiImport: NodeJS.Dict<any>; // TODO: Narrow to DOM types | ||
} | ||
declare module "node:wasi" { | ||
export * from "wasi"; | ||
} |
@@ -0,8 +1,63 @@ | ||
/** | ||
* The `node:worker_threads` module enables the use of threads that execute | ||
* JavaScript in parallel. To access it: | ||
* | ||
* ```js | ||
* const worker = require('node:worker_threads'); | ||
* ``` | ||
* | ||
* Workers (threads) are useful for performing CPU-intensive JavaScript operations. | ||
* They do not help much with I/O-intensive work. The Node.js built-in | ||
* asynchronous I/O operations are more efficient than Workers can be. | ||
* | ||
* Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do | ||
* so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`instances. | ||
* | ||
* ```js | ||
* const { | ||
* Worker, isMainThread, parentPort, workerData, | ||
* } = require('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'); | ||
* const script = workerData; | ||
* parentPort.postMessage(parse(script)); | ||
* } | ||
* ``` | ||
* | ||
* The above example spawns a Worker thread for each `parseJSAsync()` call. In | ||
* practice, use a pool of Workers for these kinds of tasks. Otherwise, the | ||
* overhead of creating Workers would likely exceed their benefit. | ||
* | ||
* When implementing a worker pool, use the `AsyncResource` API to inform | ||
* diagnostic tools (e.g. to provide asynchronous stack traces) about the | ||
* correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation. | ||
* | ||
* 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/v20.2.0/lib/worker_threads.js) | ||
*/ | ||
declare module "worker_threads" { | ||
import { Context } from "vm"; | ||
import { EventEmitter } from "events"; | ||
import { Readable, Writable } from "stream"; | ||
import { URL } from "url"; | ||
import { FileHandle } from "fs/promises"; | ||
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 { URL } from "node:url"; | ||
import { X509Certificate } from "node:crypto"; | ||
const isMainThread: boolean; | ||
@@ -14,3 +69,17 @@ const parentPort: null | MessagePort; | ||
const workerData: any; | ||
/** | ||
* Instances of the `worker.MessageChannel` class represent an asynchronous, | ||
* two-way communications channel. | ||
* 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'); | ||
* | ||
* const { port1, port2 } = new MessageChannel(); | ||
* port1.on('message', (message) => console.log('received', message)); | ||
* port2.postMessage({ foo: 'bar' }); | ||
* // Prints: received { foo: 'bar' } from the `port1.on('message')` listener | ||
* ``` | ||
* @since v10.5.0 | ||
*/ | ||
class MessageChannel { | ||
@@ -20,12 +89,122 @@ readonly port1: MessagePort; | ||
} | ||
type TransferListItem = ArrayBuffer | MessagePort | FileHandle; | ||
interface WorkerPerformance { | ||
eventLoopUtilization: EventLoopUtilityFunction; | ||
} | ||
type TransferListItem = ArrayBuffer | MessagePort | FileHandle | X509Certificate | Blob; | ||
/** | ||
* Instances of the `worker.MessagePort` class represent one end of an | ||
* asynchronous, two-way communications channel. It can be used to transfer | ||
* structured data, memory regions and other `MessagePort`s between different `Worker` s. | ||
* | ||
* This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. | ||
* @since v10.5.0 | ||
*/ | ||
class MessagePort extends EventEmitter { | ||
/** | ||
* Disables further sending of messages on either side of the connection. | ||
* This method can be called when no further communication will happen over this`MessagePort`. | ||
* | ||
* The `'close' event` is emitted on both `MessagePort` instances that | ||
* are part of the channel. | ||
* @since v10.5.0 | ||
*/ | ||
close(): void; | ||
postMessage(value: any, transferList?: ReadonlyArray<TransferListItem>): void; | ||
/** | ||
* Sends a JavaScript value to the receiving side of this channel.`value` is transferred in a way which is compatible with | ||
* the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). | ||
* | ||
* In particular, the significant differences to `JSON` are: | ||
* | ||
* * `value` may contain circular references. | ||
* * `value` may contain instances of builtin JS types such as `RegExp`s,`BigInt`s, `Map`s, `Set`s, etc. | ||
* * `value` may contain typed arrays, both using `ArrayBuffer`s | ||
* and `SharedArrayBuffer`s. | ||
* * `value` may contain [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) instances. | ||
* * `value` may not contain native (C++-backed) objects other than: | ||
* | ||
* ```js | ||
* const { MessageChannel } = require('node:worker_threads'); | ||
* const { port1, port2 } = new MessageChannel(); | ||
* | ||
* port1.on('message', (message) => console.log(message)); | ||
* | ||
* const circularData = {}; | ||
* circularData.foo = circularData; | ||
* // Prints: { foo: [Circular] } | ||
* port2.postMessage(circularData); | ||
* ``` | ||
* | ||
* `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort`, and `FileHandle` objects. | ||
* After transferring, they are not usable on the sending side of the channel | ||
* anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently | ||
* not supported. | ||
* | ||
* If `value` contains [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances, those are accessible | ||
* from either thread. They cannot be listed in `transferList`. | ||
* | ||
* `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'); | ||
* const { port1, port2 } = new MessageChannel(); | ||
* | ||
* port1.on('message', (message) => console.log(message)); | ||
* | ||
* const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]); | ||
* // This posts a copy of `uint8Array`: | ||
* port2.postMessage(uint8Array); | ||
* // This does not copy data, but renders `uint8Array` unusable: | ||
* port2.postMessage(uint8Array, [ uint8Array.buffer ]); | ||
* | ||
* // The memory for the `sharedUint8Array` is accessible from both the | ||
* // original and the copy received by `.on('message')`: | ||
* const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4)); | ||
* port2.postMessage(sharedUint8Array); | ||
* | ||
* // This transfers a freshly created message port to the receiver. | ||
* // This can be used, for example, to create communication channels between | ||
* // multiple `Worker` threads that are children of the same parent thread. | ||
* const otherChannel = new MessageChannel(); | ||
* port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]); | ||
* ``` | ||
* | ||
* The message object is cloned immediately, and can be modified after | ||
* posting without having side effects. | ||
* | ||
* For more information on the serialization and deserialization mechanisms | ||
* behind this API, see the `serialization API of the node:v8 module`. | ||
* @since v10.5.0 | ||
*/ | ||
postMessage(value: any, transferList?: readonly TransferListItem[]): void; | ||
/** | ||
* 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. | ||
* | ||
* If listeners are attached or removed using `.on('message')`, the port | ||
* is `ref()`ed and `unref()`ed automatically depending on whether | ||
* listeners for the event exist. | ||
* @since v10.5.0 | ||
*/ | ||
ref(): void; | ||
/** | ||
* Calling `unref()` on a port allows the thread to exit if this is the only | ||
* active handle in the event system. If the port is already `unref()`ed calling`unref()` again has no effect. | ||
* | ||
* If listeners are attached or removed using `.on('message')`, the port is`ref()`ed and `unref()`ed automatically depending on whether | ||
* listeners for the event exist. | ||
* @since v10.5.0 | ||
*/ | ||
unref(): void; | ||
/** | ||
* Starts receiving messages on this `MessagePort`. When using this port | ||
* as an event emitter, this is called automatically once `'message'`listeners are attached. | ||
* | ||
* This method exists for parity with the Web `MessagePort` API. In Node.js, | ||
* it is only useful for ignoring messages when no event listener is present. | ||
* Node.js also diverges in its handling of `.onmessage`. Setting it | ||
* automatically calls `.start()`, but unsetting it lets messages queue up | ||
* until a new handler is set or the port is discarded. | ||
* @since v10.5.0 | ||
*/ | ||
start(): void; | ||
addListener(event: "close", listener: () => void): this; | ||
@@ -35,3 +214,2 @@ addListener(event: "message", listener: (value: any) => void): this; | ||
addListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
emit(event: "close"): boolean; | ||
@@ -41,3 +219,2 @@ emit(event: "message", value: any): boolean; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
on(event: "close", listener: () => void): this; | ||
@@ -47,3 +224,2 @@ on(event: "message", listener: (value: any) => void): this; | ||
on(event: string | symbol, listener: (...args: any[]) => void): this; | ||
once(event: "close", listener: () => void): this; | ||
@@ -53,3 +229,2 @@ once(event: "message", listener: (value: any) => void): this; | ||
once(event: string | symbol, listener: (...args: any[]) => void): this; | ||
prependListener(event: "close", listener: () => void): this; | ||
@@ -59,3 +234,2 @@ prependListener(event: "message", listener: (value: any) => void): this; | ||
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: "close", listener: () => void): this; | ||
@@ -65,3 +239,2 @@ prependOnceListener(event: "message", listener: (value: any) => void): this; | ||
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
removeListener(event: "close", listener: () => void): this; | ||
@@ -71,3 +244,2 @@ removeListener(event: "message", listener: (value: any) => void): this; | ||
removeListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
off(event: "close", listener: () => void): this; | ||
@@ -78,3 +250,2 @@ off(event: "message", listener: (value: any) => void): this; | ||
} | ||
interface WorkerOptions { | ||
@@ -87,18 +258,26 @@ /** | ||
*/ | ||
argv?: any[]; | ||
env?: NodeJS.Dict<string> | typeof SHARE_ENV; | ||
eval?: boolean; | ||
argv?: any[] | undefined; | ||
env?: NodeJS.Dict<string> | typeof SHARE_ENV | undefined; | ||
eval?: boolean | undefined; | ||
workerData?: any; | ||
stdin?: boolean; | ||
stdout?: boolean; | ||
stderr?: boolean; | ||
execArgv?: string[]; | ||
resourceLimits?: ResourceLimits; | ||
stdin?: boolean | undefined; | ||
stdout?: boolean | undefined; | ||
stderr?: boolean | undefined; | ||
execArgv?: string[] | undefined; | ||
resourceLimits?: ResourceLimits | undefined; | ||
/** | ||
* Additional data to send in the first worker message. | ||
*/ | ||
transferList?: TransferListItem[]; | ||
trackUnmanagedFds?: boolean; | ||
transferList?: TransferListItem[] | 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 | ||
* `[worker ${id}] ${name}`. | ||
*/ | ||
name?: string | undefined; | ||
} | ||
interface ResourceLimits { | ||
@@ -108,11 +287,11 @@ /** | ||
*/ | ||
maxYoungGenerationSizeMb?: number; | ||
maxYoungGenerationSizeMb?: number | undefined; | ||
/** | ||
* The maximum size of the main heap in MB. | ||
*/ | ||
maxOldGenerationSizeMb?: number; | ||
maxOldGenerationSizeMb?: number | undefined; | ||
/** | ||
* The size of a pre-allocated memory range used for generated code. | ||
*/ | ||
codeRangeSizeMb?: number; | ||
codeRangeSizeMb?: number | undefined; | ||
/** | ||
@@ -122,13 +301,111 @@ * The default maximum stack size for the thread. Small values may lead to unusable Worker instances. | ||
*/ | ||
stackSizeMb?: number; | ||
stackSizeMb?: number | undefined; | ||
} | ||
/** | ||
* The `Worker` class represents an independent JavaScript execution thread. | ||
* Most Node.js APIs are available inside of it. | ||
* | ||
* 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. | ||
* * `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 | ||
* are not available. | ||
* * `process.env` is a copy of the parent thread's environment variables, | ||
* unless otherwise specified. Changes to one copy are not visible in other | ||
* threads, and are not visible to native add-ons (unless `worker.SHARE_ENV` is passed as the `env` option to the `Worker` constructor). On Windows, unlike the main thread, a copy of the | ||
* environment variables operates in a case-sensitive manner. | ||
* * `process.title` cannot be modified. | ||
* * Signals are not delivered through `process.on('...')`. | ||
* * Execution may stop at any point as a result of `worker.terminate()` being invoked. | ||
* * IPC channels from parent processes are not accessible. | ||
* * The `trace_events` module is not supported. | ||
* * Native add-ons can only be loaded from multiple threads if they fulfill `certain conditions`. | ||
* | ||
* Creating `Worker` instances inside of other `Worker`s is possible. | ||
* | ||
* Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication | ||
* can be achieved through inter-thread message passing. Internally, a `Worker` has | ||
* a built-in pair of `MessagePort` s that are already associated with each | ||
* other when the `Worker` is created. While the `MessagePort` object on the parent | ||
* side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event | ||
* on the `Worker` object for the parent thread. | ||
* | ||
* To create custom messaging channels (which is encouraged over using the default | ||
* global channel because it facilitates separation of concerns), users can create | ||
* a `MessageChannel` object on either thread and pass one of the`MessagePort`s on that `MessageChannel` to the other thread through a | ||
* pre-existing channel, such as the global one. | ||
* | ||
* See `port.postMessage()` for more information on how messages are passed, | ||
* and what kind of JavaScript values can be successfully transported through | ||
* the thread barrier. | ||
* | ||
* ```js | ||
* const assert = require('node:assert'); | ||
* const { | ||
* Worker, MessageChannel, MessagePort, isMainThread, parentPort, | ||
* } = require('node:worker_threads'); | ||
* if (isMainThread) { | ||
* const worker = new Worker(__filename); | ||
* const subChannel = new MessageChannel(); | ||
* worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); | ||
* subChannel.port2.on('message', (value) => { | ||
* console.log('received:', value); | ||
* }); | ||
* } else { | ||
* parentPort.once('message', (value) => { | ||
* assert(value.hereIsYourPort instanceof MessagePort); | ||
* value.hereIsYourPort.postMessage('the worker is sending this'); | ||
* value.hereIsYourPort.close(); | ||
* }); | ||
* } | ||
* ``` | ||
* @since v10.5.0 | ||
*/ | ||
class Worker extends EventEmitter { | ||
/** | ||
* If `stdin: true` was passed to the `Worker` constructor, this is a | ||
* writable stream. The data written to this stream will be made available in | ||
* the worker thread as `process.stdin`. | ||
* @since v10.5.0 | ||
*/ | ||
readonly stdin: Writable | null; | ||
/** | ||
* This is a readable stream which contains data written to `process.stdout` inside the worker thread. If `stdout: true` was not passed to the `Worker` constructor, then data is piped to the | ||
* parent thread's `process.stdout` stream. | ||
* @since v10.5.0 | ||
*/ | ||
readonly stdout: Readable; | ||
/** | ||
* This is a readable stream which contains data written to `process.stderr` inside the worker thread. If `stderr: true` was not passed to the `Worker` constructor, then data is piped to the | ||
* parent thread's `process.stderr` stream. | ||
* @since v10.5.0 | ||
*/ | ||
readonly stderr: Readable; | ||
/** | ||
* An integer identifier for the referenced thread. Inside the worker thread, | ||
* it is available as `require('node:worker_threads').threadId`. | ||
* This value is unique for each `Worker` instance inside a single process. | ||
* @since v10.5.0 | ||
*/ | ||
readonly threadId: number; | ||
readonly resourceLimits?: ResourceLimits; | ||
/** | ||
* Provides the set of JS engine resource constraints for this Worker thread. | ||
* If the `resourceLimits` option was passed to the `Worker` constructor, | ||
* this matches its values. | ||
* | ||
* If the worker has stopped, the return value is an empty object. | ||
* @since v13.2.0, v12.16.0 | ||
*/ | ||
readonly resourceLimits?: ResourceLimits | undefined; | ||
/** | ||
* An object that can be used to query performance information from a worker | ||
* instance. Similar to `perf_hooks.performance`. | ||
* @since v15.1.0, v14.17.0, v12.22.0 | ||
*/ | ||
readonly performance: WorkerPerformance; | ||
/** | ||
* @param filename The path to the Worker’s main script or module. | ||
@@ -139,22 +416,37 @@ * Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../, | ||
constructor(filename: string | URL, options?: WorkerOptions); | ||
postMessage(value: any, transferList?: ReadonlyArray<TransferListItem>): void; | ||
/** | ||
* Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`. | ||
* See `port.postMessage()` for more details. | ||
* @since v10.5.0 | ||
*/ | ||
postMessage(value: any, transferList?: readonly TransferListItem[]): void; | ||
/** | ||
* Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default | ||
* behavior). If the worker is `ref()`ed, calling `ref()` again has | ||
* no effect. | ||
* @since v10.5.0 | ||
*/ | ||
ref(): void; | ||
/** | ||
* Calling `unref()` on a worker allows the thread to exit if this is the only | ||
* active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect. | ||
* @since v10.5.0 | ||
*/ | ||
unref(): void; | ||
/** | ||
* Stop all JavaScript execution in the worker thread as soon as possible. | ||
* Returns a Promise for the exit code that is fulfilled when the `exit` event is emitted. | ||
* Returns a Promise for the exit code that is fulfilled when the `'exit' event` is emitted. | ||
* @since v10.5.0 | ||
*/ | ||
terminate(): Promise<number>; | ||
/** | ||
* Returns a readable stream for a V8 snapshot of the current state of the Worker. | ||
* See [`v8.getHeapSnapshot()`][] for more details. | ||
* See `v8.getHeapSnapshot()` for more details. | ||
* | ||
* If the Worker thread is no longer running, which may occur before the | ||
* [`'exit'` event][] is emitted, the returned `Promise` will be rejected | ||
* immediately with an [`ERR_WORKER_NOT_RUNNING`][] error | ||
* If the Worker thread is no longer running, which may occur before the `'exit' event` is emitted, the returned `Promise` is rejected | ||
* immediately with an `ERR_WORKER_NOT_RUNNING` error. | ||
* @since v13.9.0, v12.17.0 | ||
* @return A promise for a Readable Stream containing a V8 heap snapshot | ||
*/ | ||
getHeapSnapshot(): Promise<Readable>; | ||
addListener(event: "error", listener: (err: Error) => void): this; | ||
@@ -166,3 +458,2 @@ addListener(event: "exit", listener: (exitCode: number) => void): this; | ||
addListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
emit(event: "error", err: Error): boolean; | ||
@@ -174,3 +465,2 @@ emit(event: "exit", exitCode: number): boolean; | ||
emit(event: string | symbol, ...args: any[]): boolean; | ||
on(event: "error", listener: (err: Error) => void): this; | ||
@@ -182,3 +472,2 @@ on(event: "exit", listener: (exitCode: number) => void): this; | ||
on(event: string | symbol, listener: (...args: any[]) => void): this; | ||
once(event: "error", listener: (err: Error) => void): this; | ||
@@ -190,3 +479,2 @@ once(event: "exit", listener: (exitCode: number) => void): this; | ||
once(event: string | symbol, listener: (...args: any[]) => void): this; | ||
prependListener(event: "error", listener: (err: Error) => void): this; | ||
@@ -198,3 +486,2 @@ prependListener(event: "exit", listener: (exitCode: number) => void): this; | ||
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
prependOnceListener(event: "error", listener: (err: Error) => void): this; | ||
@@ -206,3 +493,2 @@ prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; | ||
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
removeListener(event: "error", listener: (err: Error) => void): this; | ||
@@ -214,3 +500,2 @@ removeListener(event: "exit", listener: (exitCode: number) => void): this; | ||
removeListener(event: string | symbol, listener: (...args: any[]) => void): this; | ||
off(event: "error", listener: (err: Error) => void): this; | ||
@@ -223,38 +508,206 @@ off(event: "exit", listener: (exitCode: number) => void): this; | ||
} | ||
interface BroadcastChannel extends NodeJS.RefCounted {} | ||
/** | ||
* Mark an object as not transferable. | ||
* If `object` occurs in the transfer list of a `port.postMessage()` call, it will be ignored. | ||
* Instances of `BroadcastChannel` allow asynchronous one-to-many communication | ||
* with all other `BroadcastChannel` instances bound to the same channel name. | ||
* | ||
* In particular, this makes sense for objects that can be cloned, rather than transferred, | ||
* and which are used by other objects on the sending side. For example, Node.js marks | ||
* the `ArrayBuffer`s it uses for its Buffer pool with this. | ||
* ```js | ||
* 'use strict'; | ||
* | ||
* const { | ||
* isMainThread, | ||
* BroadcastChannel, | ||
* Worker, | ||
* } = require('node:worker_threads'); | ||
* | ||
* const bc = new BroadcastChannel('hello'); | ||
* | ||
* if (isMainThread) { | ||
* let c = 0; | ||
* bc.onmessage = (event) => { | ||
* console.log(event.data); | ||
* if (++c === 10) bc.close(); | ||
* }; | ||
* for (let n = 0; n < 10; n++) | ||
* new Worker(__filename); | ||
* } else { | ||
* bc.postMessage('hello from every worker'); | ||
* bc.close(); | ||
* } | ||
* ``` | ||
* @since v15.4.0 | ||
*/ | ||
class BroadcastChannel { | ||
readonly name: string; | ||
/** | ||
* Invoked with a single \`MessageEvent\` argument when a message is received. | ||
* @since v15.4.0 | ||
*/ | ||
onmessage: (message: unknown) => void; | ||
/** | ||
* Invoked with a received message cannot be deserialized. | ||
* @since v15.4.0 | ||
*/ | ||
onmessageerror: (message: unknown) => void; | ||
constructor(name: string); | ||
/** | ||
* Closes the `BroadcastChannel` connection. | ||
* @since v15.4.0 | ||
*/ | ||
close(): void; | ||
/** | ||
* @since v15.4.0 | ||
* @param message Any cloneable JavaScript value. | ||
*/ | ||
postMessage(message: unknown): void; | ||
} | ||
/** | ||
* Mark an object as not transferable. If `object` occurs in the transfer list of | ||
* a `port.postMessage()` call, it is ignored. | ||
* | ||
* In particular, this makes sense for objects that can be cloned, rather than | ||
* transferred, and which are used by other objects on the sending side. | ||
* For example, Node.js marks the `ArrayBuffer`s it uses for its `Buffer pool` with this. | ||
* | ||
* This operation cannot be undone. | ||
* | ||
* ```js | ||
* const { MessageChannel, markAsUntransferable } = require('node:worker_threads'); | ||
* | ||
* const pooledBuffer = new ArrayBuffer(8); | ||
* const typedArray1 = new Uint8Array(pooledBuffer); | ||
* const typedArray2 = new Float64Array(pooledBuffer); | ||
* | ||
* markAsUntransferable(pooledBuffer); | ||
* | ||
* const { port1 } = new MessageChannel(); | ||
* port1.postMessage(typedArray1, [ typedArray1.buffer ]); | ||
* | ||
* // The following line prints the contents of typedArray1 -- it still owns | ||
* // its memory and has been cloned, not transferred. Without | ||
* // `markAsUntransferable()`, this would print an empty Uint8Array. | ||
* // typedArray2 is intact as well. | ||
* console.log(typedArray1); | ||
* console.log(typedArray2); | ||
* ``` | ||
* | ||
* There is no equivalent to this API in browsers. | ||
* @since v14.5.0, v12.19.0 | ||
*/ | ||
function markAsUntransferable(object: object): void; | ||
/** | ||
* Transfer a `MessagePort` to a different `vm` Context. The original `port` | ||
* object will be rendered unusable, and the returned `MessagePort` instance will | ||
* take its place. | ||
* Transfer a `MessagePort` to a different `vm` Context. The original `port`object is rendered unusable, and the returned `MessagePort` instance | ||
* takes its place. | ||
* | ||
* The returned `MessagePort` will be an object in the target context, and will | ||
* inherit from its global `Object` class. Objects passed to the | ||
* `port.onmessage()` listener will also be created in the target context | ||
* The returned `MessagePort` is an object in the target context and | ||
* inherits from its global `Object` class. Objects passed to the [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) listener are also created in the | ||
* target context | ||
* and inherit from its global `Object` class. | ||
* | ||
* However, the created `MessagePort` will no longer inherit from | ||
* `EventEmitter`, and only `port.onmessage()` can be used to receive | ||
* However, the created `MessagePort` no longer inherits from [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), and only | ||
* [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) can be used to receive | ||
* events using it. | ||
* @since v11.13.0 | ||
* @param port The message port to transfer. | ||
* @param contextifiedSandbox A `contextified` object as returned by the `vm.createContext()` method. | ||
*/ | ||
function moveMessagePortToContext(port: MessagePort, context: Context): MessagePort; | ||
function moveMessagePortToContext(port: MessagePort, contextifiedSandbox: Context): MessagePort; | ||
/** | ||
* Receive a single message from a given `MessagePort`. If no message is available, | ||
* `undefined` is returned, otherwise an object with a single `message` property | ||
* that contains the message payload, corresponding to the oldest message in the | ||
* `MessagePort`’s queue. | ||
* Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property | ||
* that contains the message payload, corresponding to the oldest message in the`MessagePort`'s queue. | ||
* | ||
* ```js | ||
* const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads'); | ||
* const { port1, port2 } = new MessageChannel(); | ||
* port1.postMessage({ hello: 'world' }); | ||
* | ||
* console.log(receiveMessageOnPort(port2)); | ||
* // Prints: { message: { hello: 'world' } } | ||
* console.log(receiveMessageOnPort(port2)); | ||
* // Prints: undefined | ||
* ``` | ||
* | ||
* When this function is used, no `'message'` event is emitted and the`onmessage` listener is not invoked. | ||
* @since v12.3.0 | ||
*/ | ||
function receiveMessageOnPort(port: MessagePort): { message: any } | undefined; | ||
function receiveMessageOnPort(port: MessagePort): | ||
| { | ||
message: any; | ||
} | ||
| undefined; | ||
type Serializable = string | object | number | boolean | bigint; | ||
/** | ||
* Within a worker thread, `worker.getEnvironmentData()` returns a clone | ||
* of data passed to the spawning thread's `worker.setEnvironmentData()`. | ||
* Every new `Worker` receives its own copy of the environment data | ||
* automatically. | ||
* | ||
* ```js | ||
* const { | ||
* Worker, | ||
* isMainThread, | ||
* setEnvironmentData, | ||
* getEnvironmentData, | ||
* } = require('node:worker_threads'); | ||
* | ||
* if (isMainThread) { | ||
* setEnvironmentData('Hello', 'World!'); | ||
* const worker = new Worker(__filename); | ||
* } else { | ||
* console.log(getEnvironmentData('Hello')); // Prints 'World!'. | ||
* } | ||
* ``` | ||
* @since v15.12.0, v14.18.0 | ||
* @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. | ||
*/ | ||
function getEnvironmentData(key: Serializable): Serializable; | ||
/** | ||
* The `worker.setEnvironmentData()` API sets the content of`worker.getEnvironmentData()` in the current thread and all new `Worker`instances spawned from the current context. | ||
* @since v15.12.0, v14.18.0 | ||
* @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. | ||
* @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; | ||
import { | ||
BroadcastChannel as _BroadcastChannel, | ||
MessageChannel as _MessageChannel, | ||
MessagePort as _MessagePort, | ||
} from "worker_threads"; | ||
global { | ||
/** | ||
* `BroadcastChannel` class is a global reference for `require('worker_threads').BroadcastChannel` | ||
* https://nodejs.org/api/globals.html#broadcastchannel | ||
* @since v18.0.0 | ||
*/ | ||
var BroadcastChannel: typeof globalThis extends { | ||
onmessage: any; | ||
BroadcastChannel: infer T; | ||
} ? T | ||
: typeof _BroadcastChannel; | ||
/** | ||
* `MessageChannel` class is a global reference for `require('worker_threads').MessageChannel` | ||
* https://nodejs.org/api/globals.html#messagechannel | ||
* @since v15.0.0 | ||
*/ | ||
var MessageChannel: typeof globalThis extends { | ||
onmessage: any; | ||
MessageChannel: infer T; | ||
} ? T | ||
: typeof _MessageChannel; | ||
/** | ||
* `MessagePort` class is a global reference for `require('worker_threads').MessagePort` | ||
* https://nodejs.org/api/globals.html#messageport | ||
* @since v15.0.0 | ||
*/ | ||
var MessagePort: typeof globalThis extends { | ||
onmessage: any; | ||
MessagePort: infer T; | ||
} ? T | ||
: typeof _MessagePort; | ||
} | ||
} | ||
declare module "node:worker_threads" { | ||
export * from "worker_threads"; | ||
} |
@@ -0,4 +1,95 @@ | ||
/** | ||
* The `node:zlib` module provides compression functionality implemented using | ||
* Gzip, Deflate/Inflate, and Brotli. | ||
* | ||
* To access it: | ||
* | ||
* ```js | ||
* const zlib = require('node:zlib'); | ||
* ``` | ||
* | ||
* Compression and decompression are built around the Node.js `Streams API`. | ||
* | ||
* 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 { | ||
* createReadStream, | ||
* createWriteStream, | ||
* } = require('node:fs'); | ||
* | ||
* const gzip = createGzip(); | ||
* const source = createReadStream('input.txt'); | ||
* const destination = createWriteStream('input.txt.gz'); | ||
* | ||
* pipeline(source, gzip, destination, (err) => { | ||
* if (err) { | ||
* console.error('An error occurred:', err); | ||
* process.exitCode = 1; | ||
* } | ||
* }); | ||
* | ||
* // Or, Promisified | ||
* | ||
* const { promisify } = require('node:util'); | ||
* const pipe = promisify(pipeline); | ||
* | ||
* async function do_gzip(input, output) { | ||
* const gzip = createGzip(); | ||
* const source = createReadStream(input); | ||
* const destination = createWriteStream(output); | ||
* await pipe(source, gzip, destination); | ||
* } | ||
* | ||
* do_gzip('input.txt', 'input.txt.gz') | ||
* .catch((err) => { | ||
* console.error('An error occurred:', err); | ||
* process.exitCode = 1; | ||
* }); | ||
* ``` | ||
* | ||
* It is also possible to compress or decompress data in a single step: | ||
* | ||
* ```js | ||
* const { deflate, unzip } = require('node:zlib'); | ||
* | ||
* const input = '.................................'; | ||
* deflate(input, (err, buffer) => { | ||
* if (err) { | ||
* console.error('An error occurred:', err); | ||
* process.exitCode = 1; | ||
* } | ||
* console.log(buffer.toString('base64')); | ||
* }); | ||
* | ||
* const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64'); | ||
* unzip(buffer, (err, buffer) => { | ||
* if (err) { | ||
* console.error('An error occurred:', err); | ||
* process.exitCode = 1; | ||
* } | ||
* console.log(buffer.toString()); | ||
* }); | ||
* | ||
* // Or, Promisified | ||
* | ||
* const { promisify } = require('node:util'); | ||
* const do_unzip = promisify(unzip); | ||
* | ||
* do_unzip(buffer) | ||
* .then((buf) => console.log(buf.toString())) | ||
* .catch((err) => { | ||
* console.error('An error occurred:', err); | ||
* process.exitCode = 1; | ||
* }); | ||
* ``` | ||
* @since v0.5.8 | ||
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/zlib.js) | ||
*/ | ||
declare module "zlib" { | ||
import * as stream from "stream"; | ||
import * as stream from "node:stream"; | ||
interface ZlibOptions { | ||
@@ -8,20 +99,19 @@ /** | ||
*/ | ||
flush?: number; | ||
flush?: number | undefined; | ||
/** | ||
* @default constants.Z_FINISH | ||
*/ | ||
finishFlush?: number; | ||
finishFlush?: number | undefined; | ||
/** | ||
* @default 16*1024 | ||
*/ | ||
chunkSize?: number; | ||
windowBits?: number; | ||
level?: number; // compression only | ||
memLevel?: number; // compression only | ||
strategy?: number; // compression only | ||
dictionary?: NodeJS.ArrayBufferView | ArrayBuffer; // deflate/inflate only, empty dictionary by default | ||
info?: boolean; | ||
maxOutputLength?: number; | ||
chunkSize?: number | undefined; | ||
windowBits?: number | undefined; | ||
level?: number | undefined; // compression only | ||
memLevel?: number | undefined; // compression only | ||
strategy?: number | undefined; // compression only | ||
dictionary?: NodeJS.ArrayBufferView | ArrayBuffer | undefined; // deflate/inflate only, empty dictionary by default | ||
info?: boolean | undefined; | ||
maxOutputLength?: number | undefined; | ||
} | ||
interface BrotliOptions { | ||
@@ -31,20 +121,21 @@ /** | ||
*/ | ||
flush?: number; | ||
flush?: number | undefined; | ||
/** | ||
* @default constants.BROTLI_OPERATION_FINISH | ||
*/ | ||
finishFlush?: number; | ||
finishFlush?: number | undefined; | ||
/** | ||
* @default 16*1024 | ||
*/ | ||
chunkSize?: number; | ||
params?: { | ||
/** | ||
* Each key is a `constants.BROTLI_*` constant. | ||
*/ | ||
[key: number]: boolean | number; | ||
}; | ||
maxOutputLength?: number; | ||
chunkSize?: number | undefined; | ||
params?: | ||
| { | ||
/** | ||
* Each key is a `constants.BROTLI_*` constant. | ||
*/ | ||
[key: number]: boolean | number; | ||
} | ||
| undefined; | ||
maxOutputLength?: number | undefined; | ||
} | ||
interface Zlib { | ||
@@ -54,3 +145,3 @@ /** @deprecated Use bytesWritten instead. */ | ||
readonly bytesWritten: number; | ||
shell?: boolean | string; | ||
shell?: boolean | string | undefined; | ||
close(callback?: () => void): void; | ||
@@ -60,35 +151,74 @@ flush(kind?: number, callback?: () => void): void; | ||
} | ||
interface ZlibParams { | ||
params(level: number, strategy: number, callback: () => void): void; | ||
} | ||
interface ZlibReset { | ||
reset(): void; | ||
} | ||
interface BrotliCompress extends stream.Transform, Zlib { } | ||
interface BrotliDecompress extends stream.Transform, Zlib { } | ||
interface Gzip extends stream.Transform, Zlib { } | ||
interface Gunzip extends stream.Transform, Zlib { } | ||
interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } | ||
interface Inflate extends stream.Transform, Zlib, ZlibReset { } | ||
interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } | ||
interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } | ||
interface Unzip extends stream.Transform, Zlib { } | ||
interface BrotliCompress extends stream.Transform, Zlib {} | ||
interface BrotliDecompress extends stream.Transform, Zlib {} | ||
interface Gzip extends stream.Transform, Zlib {} | ||
interface Gunzip extends stream.Transform, Zlib {} | ||
interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams {} | ||
interface Inflate extends stream.Transform, Zlib, ZlibReset {} | ||
interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams {} | ||
interface InflateRaw extends stream.Transform, Zlib, ZlibReset {} | ||
interface Unzip extends stream.Transform, Zlib {} | ||
/** | ||
* Creates and returns a new `BrotliCompress` object. | ||
* @since v11.7.0, v10.16.0 | ||
*/ | ||
function createBrotliCompress(options?: BrotliOptions): BrotliCompress; | ||
/** | ||
* Creates and returns a new `BrotliDecompress` object. | ||
* @since v11.7.0, v10.16.0 | ||
*/ | ||
function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; | ||
/** | ||
* Creates and returns a new `Gzip` object. | ||
* See `example`. | ||
* @since v0.5.8 | ||
*/ | ||
function createGzip(options?: ZlibOptions): Gzip; | ||
/** | ||
* Creates and returns a new `Gunzip` object. | ||
* @since v0.5.8 | ||
*/ | ||
function createGunzip(options?: ZlibOptions): Gunzip; | ||
/** | ||
* Creates and returns a new `Deflate` object. | ||
* @since v0.5.8 | ||
*/ | ||
function createDeflate(options?: ZlibOptions): Deflate; | ||
/** | ||
* Creates and returns a new `Inflate` object. | ||
* @since v0.5.8 | ||
*/ | ||
function createInflate(options?: ZlibOptions): Inflate; | ||
/** | ||
* Creates and returns a new `DeflateRaw` object. | ||
* | ||
* An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`is set to 8 for raw deflate streams. zlib would automatically set `windowBits`to 9 if was initially set to 8\. Newer | ||
* versions of zlib will throw an exception, | ||
* so Node.js restored the original behavior of upgrading a value of 8 to 9, | ||
* since passing `windowBits = 9` to zlib actually results in a compressed stream | ||
* that effectively uses an 8-bit window only. | ||
* @since v0.5.8 | ||
*/ | ||
function createDeflateRaw(options?: ZlibOptions): DeflateRaw; | ||
/** | ||
* Creates and returns a new `InflateRaw` object. | ||
* @since v0.5.8 | ||
*/ | ||
function createInflateRaw(options?: ZlibOptions): InflateRaw; | ||
/** | ||
* Creates and returns a new `Unzip` object. | ||
* @since v0.5.8 | ||
*/ | ||
function createUnzip(options?: ZlibOptions): Unzip; | ||
type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView; | ||
type CompressCallback = (error: Error | null, result: Buffer) => void; | ||
/** | ||
* @since v11.7.0, v10.16.0 | ||
*/ | ||
function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; | ||
@@ -99,5 +229,10 @@ function brotliCompress(buf: InputType, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Compress a chunk of data with `BrotliCompress`. | ||
* @since v11.7.0, v10.16.0 | ||
*/ | ||
function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; | ||
/** | ||
* @since v11.7.0, v10.16.0 | ||
*/ | ||
function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; | ||
@@ -108,5 +243,10 @@ function brotliDecompress(buf: InputType, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Decompress a chunk of data with `BrotliDecompress`. | ||
* @since v11.7.0, v10.16.0 | ||
*/ | ||
function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function deflate(buf: InputType, callback: CompressCallback): void; | ||
@@ -117,5 +257,10 @@ function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Compress a chunk of data with `Deflate`. | ||
* @since v0.11.12 | ||
*/ | ||
function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function deflateRaw(buf: InputType, callback: CompressCallback): void; | ||
@@ -126,5 +271,10 @@ function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Compress a chunk of data with `DeflateRaw`. | ||
* @since v0.11.12 | ||
*/ | ||
function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function gzip(buf: InputType, callback: CompressCallback): void; | ||
@@ -135,5 +285,10 @@ function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Compress a chunk of data with `Gzip`. | ||
* @since v0.11.12 | ||
*/ | ||
function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function gunzip(buf: InputType, callback: CompressCallback): void; | ||
@@ -144,5 +299,10 @@ function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Decompress a chunk of data with `Gunzip`. | ||
* @since v0.11.12 | ||
*/ | ||
function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function inflate(buf: InputType, callback: CompressCallback): void; | ||
@@ -153,5 +313,10 @@ function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Decompress a chunk of data with `Inflate`. | ||
* @since v0.11.12 | ||
*/ | ||
function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function inflateRaw(buf: InputType, callback: CompressCallback): void; | ||
@@ -162,5 +327,10 @@ function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Decompress a chunk of data with `InflateRaw`. | ||
* @since v0.11.12 | ||
*/ | ||
function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
/** | ||
* @since v0.6.0 | ||
*/ | ||
function unzip(buf: InputType, callback: CompressCallback): void; | ||
@@ -171,5 +341,7 @@ function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; | ||
} | ||
/** | ||
* Decompress a chunk of data with `Unzip`. | ||
* @since v0.11.12 | ||
*/ | ||
function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; | ||
namespace constants { | ||
@@ -212,3 +384,2 @@ const BROTLI_DECODE: number; | ||
const BROTLI_DECODER_SUCCESS: number; | ||
const BROTLI_DEFAULT_MODE: number; | ||
@@ -225,7 +396,5 @@ const BROTLI_DEFAULT_QUALITY: number; | ||
const BROTLI_MIN_WINDOW_BITS: number; | ||
const BROTLI_MODE_FONT: number; | ||
const BROTLI_MODE_GENERIC: number; | ||
const BROTLI_MODE_TEXT: number; | ||
const BROTLI_OPERATION_EMIT_METADATA: number; | ||
@@ -235,3 +404,2 @@ const BROTLI_OPERATION_FINISH: number; | ||
const BROTLI_OPERATION_PROCESS: number; | ||
const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; | ||
@@ -246,3 +414,2 @@ const BROTLI_PARAM_LARGE_WINDOW: number; | ||
const BROTLI_PARAM_SIZE_HINT: number; | ||
const DEFLATE: number; | ||
@@ -255,3 +422,2 @@ const DEFLATERAW: number; | ||
const UNZIP: number; | ||
// Allowed flush values. | ||
@@ -265,3 +431,2 @@ const Z_NO_FLUSH: number; | ||
const Z_TREES: number; | ||
// Return codes for the compression/decompression functions. | ||
@@ -278,3 +443,2 @@ // Negative values are errors, positive values are used for special but normal events. | ||
const Z_VERSION_ERROR: number; | ||
// Compression levels. | ||
@@ -285,3 +449,2 @@ const Z_NO_COMPRESSION: number; | ||
const Z_DEFAULT_COMPRESSION: number; | ||
// Compression strategy. | ||
@@ -293,22 +456,16 @@ const Z_FILTERED: 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_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; | ||
} | ||
// Allowed flush values. | ||
@@ -329,3 +486,2 @@ /** @deprecated Use `constants.Z_NO_FLUSH` */ | ||
const Z_TREES: number; | ||
// Return codes for the compression/decompression functions. | ||
@@ -351,3 +507,2 @@ // Negative values are errors, positive values are used for special but normal events. | ||
const Z_VERSION_ERROR: number; | ||
// Compression levels. | ||
@@ -362,3 +517,2 @@ /** @deprecated Use `constants.Z_NO_COMPRESSION` */ | ||
const Z_DEFAULT_COMPRESSION: number; | ||
// Compression strategy. | ||
@@ -375,3 +529,2 @@ /** @deprecated Use `constants.Z_FILTERED` */ | ||
const Z_DEFAULT_STRATEGY: number; | ||
/** @deprecated */ | ||
@@ -388,1 +541,4 @@ const Z_BINARY: number; | ||
} | ||
declare module "node:zlib" { | ||
export * from "zlib"; | ||
} |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
3922463
111
88690
0
1
16
+ Addedundici-types@~5.26.4
+ Addedundici-types@5.26.5(transitive)