diff --git a/Gruntfile.js b/Gruntfile.js index dcb96a2c0..44f4c97f6 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -408,7 +408,7 @@ module.exports = function(grunt) { { cwd: 'packages/node_modules/@node-red/editor-client/src', src: [ - 'types/node/*.ts', + 'types/node/**/*.ts', 'types/node-red/*.ts', ], expand: true, diff --git a/packages/node_modules/@node-red/editor-client/src/js/ui/editors/code-editors/monaco.js b/packages/node_modules/@node-red/editor-client/src/js/ui/editors/code-editors/monaco.js index 68b9a487e..12d14726f 100644 --- a/packages/node_modules/@node-red/editor-client/src/js/ui/editors/code-editors/monaco.js +++ b/packages/node_modules/@node-red/editor-client/src/js/ui/editors/code-editors/monaco.js @@ -59,18 +59,21 @@ RED.editor.codeEditor.monaco = (function() { //TODO: get from externalModules.js For now this is enough for feature parity with ACE (and then some). const knownModules = { "assert": {package: "node", module: "assert", path: "node/assert.d.ts" }, + "assert/strict": {package: "node", module: "assert/strict", path: "node/assert/strict.d.ts" }, "async_hooks": {package: "node", module: "async_hooks", path: "node/async_hooks.d.ts" }, "buffer": {package: "node", module: "buffer", path: "node/buffer.d.ts" }, "child_process": {package: "node", module: "child_process", path: "node/child_process.d.ts" }, "cluster": {package: "node", module: "cluster", path: "node/cluster.d.ts" }, "console": {package: "node", module: "console", path: "node/console.d.ts" }, - "constants": {package: "node", module: "constants", path: "node/constants.d.ts" }, "crypto": {package: "node", module: "crypto", path: "node/crypto.d.ts" }, "dgram": {package: "node", module: "dgram", path: "node/dgram.d.ts" }, + "diagnostics_channel.d": {package: "node", module: "diagnostics_channel", path: "node/diagnostics_channel.d.ts" }, "dns": {package: "node", module: "dns", path: "node/dns.d.ts" }, + "dns/promises": {package: "node", module: "dns/promises", path: "node/dns/promises.d.ts" }, "domain": {package: "node", module: "domain", path: "node/domain.d.ts" }, "events": {package: "node", module: "events", path: "node/events.d.ts" }, "fs": {package: "node", module: "fs", path: "node/fs.d.ts" }, + "fs/promises": {package: "node", module: "fs/promises", path: "node/fs/promises.d.ts" }, "globals": {package: "node", module: "globals", path: "node/globals.d.ts" }, "http": {package: "node", module: "http", path: "node/http.d.ts" }, "http2": {package: "node", module: "http2", path: "node/http2.d.ts" }, @@ -84,8 +87,13 @@ RED.editor.codeEditor.monaco = (function() { "querystring": {package: "node", module: "querystring", path: "node/querystring.d.ts" }, "readline": {package: "node", module: "readline", path: "node/readline.d.ts" }, "stream": {package: "node", module: "stream", path: "node/stream.d.ts" }, + "stream/consumers": {package: "node", module: "stream/consumers", path: "node/stream/consumers.d.ts" }, + "stream/promises": {package: "node", module: "stream/promises", path: "node/stream/promises.d.ts" }, + "stream/web": {package: "node", module: "stream/web", path: "node/stream/web.d.ts" }, "string_decoder": {package: "node", module: "string_decoder", path: "node/string_decoder.d.ts" }, + "test": {package: "node", module: "test", path: "node/test.d.ts" }, "timers": {package: "node", module: "timers", path: "node/timers.d.ts" }, + "timers/promises": {package: "node", module: "timers/promises", path: "node/timers/promises.d.ts" }, "tls": {package: "node", module: "tls", path: "node/tls.d.ts" }, "trace_events": {package: "node", module: "trace_events", path: "node/trace_events.d.ts" }, "tty": {package: "node", module: "tty", path: "node/tty.d.ts" }, diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/assert.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/assert.d.ts index 6fcb3ce62..4cfbb7321 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/assert.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/assert.d.ts @@ -1,24 +1,36 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/assert.js) + */ declare module 'assert' { - /** An alias of `assert.ok()`. */ - function assert(value: any, message?: string | Error): asserts value; + /** + * 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 `assert` module + * will be instances of the `AssertionError` class. + */ class AssertionError extends Error { - actual: any; - expected: any; + actual: unknown; + expected: unknown; operator: string; generatedMessage: boolean; code: 'ERR_ASSERTION'; - constructor(options?: { /** If provided, the error message is set to this value. */ 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 | undefined; /** If provided, the generated stack trace omits frames before this function. */ @@ -26,13 +38,146 @@ declare module 'assert' { stackStartFn?: Function | undefined; }); } - + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ 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 '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 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: this, arguments: [1, 2, 3 ] }]); + * ``` + * + * @since v18.8.0, v16.18.0 + * @params fn + * @returns An Array with 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 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // 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() + * 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 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 + * tracker.getCalls(callsfunc).length === 1; + * + * tracker.reset(callsfunc); + * 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 '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 { message: string; /** The actual number of times the function was called. */ @@ -44,74 +189,764 @@ declare module 'assert' { /** A stack trace of the function. */ stack: object; } - - 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 '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 - stackStartFn?: Function, + 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(actual: any, expected: T, message?: string | Error): asserts actual is T; - function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(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) | Promise, message?: string | Error): Promise; - function rejects( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; - function doesNotReject( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - + /** + * 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 '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 '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 [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled + * and treated as being identical in case both sides are `NaN`. + * + * ```js + * import assert from '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 [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as + * being identical in case both + * sides are `NaN`. + * + * ```js + * import assert from '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 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(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 the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from '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(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from '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(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from '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 '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: + * 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: + * 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 '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 '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 '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 '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 '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 '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 '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 '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 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from '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 '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) | Promise, message?: string | Error): Promise; + function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * 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 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from '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 '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; + const strict: Omit & { + (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. @@ -122,7 +957,6 @@ declare module 'assert' { strict: typeof strict; }; } - export = assert; } declare module 'node:assert' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/assert/strict.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/assert/strict.d.ts new file mode 100644 index 000000000..ada209ced --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/assert/strict.d.ts @@ -0,0 +1,11 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +declare module 'assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} +declare module 'node:assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/async_hooks.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/async_hooks.d.ts index c576ec7c7..206104c55 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/async_hooks.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/async_hooks.d.ts @@ -2,18 +2,49 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ /** - * Async Hooks module: https://nodejs.org/api/async_hooks.html + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/async_hooks.js) */ declare module 'async_hooks' { /** - * Returns the asyncId of the current execution context. + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * 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 * Node.js handle objects with undocumented APIs. Using any functions or properties * on the object is likely to crash your application and should be avoided. @@ -21,14 +52,70 @@ declare module 'async_hooks' { * Using `executionAsyncResource()` in the top-level execution context will * return an empty object as there is no handle or request object to use, * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from '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 '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 { /** * Called when a class is constructed that has the possibility to emit an asynchronous event. @@ -38,73 +125,133 @@ declare module 'async_hooks' { * @param resource reference to the resource representing the async operation, needs to be released during destroy */ init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; - /** * When an asynchronous operation is initiated or completes a callback is called to notify the user. * The before callback is called just before said callback is executed. * @param asyncId the unique identifier assigned to the resource about to execute the callback. */ before?(asyncId: number): void; - /** * Called immediately after the callback specified in before is completed. * @param asyncId the unique identifier assigned to the resource which has executed the callback. */ after?(asyncId: number): void; - /** * Called when a promise has resolve() called. This may not be in the same execution id * as the promise itself. * @param asyncId the unique id for the promise that was resolve()d. */ promiseResolve?(asyncId: number): void; - /** * Called after the resource corresponding to asyncId is destroyed * @param asyncId a unique ID for the async resource */ destroy?(asyncId: number): void; } - interface AsyncHook { /** * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. */ enable(): this; - /** * 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. */ disable(): this; } - /** - * 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 '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 | 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 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 '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(); + * ``` */ class AsyncResource { /** @@ -114,115 +261,236 @@ declare module 'async_hooks' { * @param type The type of async event. * @param triggerAsyncId The ID of the execution context that created * 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. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @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 any>(fn: Func, type?: string): Func & { asyncResource: AsyncResource }; - + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg + ): Func & { + asyncResource: AsyncResource; + }; /** * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 * @param fn The function to bind to the current `AsyncResource`. */ - bind any>(fn: Func): Func & { asyncResource: AsyncResource }; - + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; /** - * 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(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(): 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 `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 'http'; + * import { AsyncLocalStorage } from '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 data. + * @since v13.10.0, v12.17.0 */ class AsyncLocalStorage { /** - * This method disables the instance of `AsyncLocalStorage`. All subsequent calls - * to `asyncLocalStorage.getStore()` will return `undefined` until - * `asyncLocalStorage.run()` is called again. + * 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 + * Runs a function synchronously within a context and returns its * return value. The store is not accessible outside of the callback function or * the 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 + * 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(store: T, callback: (...args: any[]) => R, ...args: any[]): R; - + run(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(callback: (...args: any[]) => R, ...args: any[]): R; - + exit(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 */ enterWith(store: T): void; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/buffer.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/buffer.d.ts index 24a77e1e4..e04af96e7 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/buffer.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/buffer.d.ts @@ -1,8 +1,54 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/buffer.js) + */ declare module 'buffer' { import { BinaryLike } from 'node:crypto'; + import { ReadableStream as WebReadableStream } from 'node:stream/web'; export const INSPECT_MAX_BYTES: number; export const kMaxLength: number; export const kStringMaxLength: number; @@ -10,17 +56,49 @@ declare module 'buffer' { MAX_LENGTH: number; MAX_STRING_LENGTH: number; }; - const BuffType: typeof Buffer; - - export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; - + export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; - export const SlowBuffer: { /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ - new(size: number): Buffer; + new (size: number): Buffer; prototype: Buffer; }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; /** * @experimental */ @@ -39,18 +117,18 @@ declare module 'buffer' { /** * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across * multiple worker threads. - * @since v14.18.0 + * @since v15.7.0 * @experimental */ export class Blob { /** * The total size of the `Blob` in bytes. - * @since v14.18.0 + * @since v15.7.0 */ readonly size: number; /** * The content-type of the `Blob`. - * @since v14.18.0 + * @since v15.7.0 */ readonly type: string; /** @@ -65,13 +143,13 @@ declare module 'buffer' { /** * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of * the `Blob` data. - * @since v14.18.0 + * @since v15.7.0 */ arrayBuffer(): Promise; /** * Creates and returns a new `Blob` containing a subset of this `Blob` objects * data. The original `Blob` is not altered. - * @since v14.18.0 + * @since v15.7.0 * @param start The starting index. * @param end The ending index. * @param type The content-type for the new `Blob` @@ -80,12 +158,2078 @@ declare module 'buffer' { /** * Returns a promise that fulfills with the contents of the `Blob` decoded as a * UTF-8 string. - * @since v14.18.0 + * @since v15.7.0 */ text(): Promise; + /** + * Returns a new (WHATWG) `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: 'string'): string; + }, + encoding?: BufferEncoding + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`,`Buffer.from(array)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. A zero-length `Buffer` is created + * if `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and_may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: 'Buffer'; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This is the same behavior as `buf.subarray()`. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * ``` + * @since v0.3.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.slice()`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0 + * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; } - - export { BuffType as Buffer }; } declare module 'node:buffer' { export * from 'buffer'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/child_process.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/child_process.d.ts index a56583b28..d79c74a3b 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/child_process.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/child_process.d.ts @@ -1,42 +1,518 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if it is in the `options` object. Otherwise, `process.env.PATH` is + * used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/child_process.js) + */ declare module 'child_process' { - import { BaseEncodingOptions } from 'fs'; - import * as events from 'events'; - import * as net from 'net'; - import { Writable, Readable, Stream, Pipe } from 'stream'; - - type Serializable = string | object | number | boolean; + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; type SendHandle = net.Socket | net.Server; - - interface ChildProcess extends events.EventEmitter { + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ readonly stdio: [ - Writable | null, // stdin - Readable | null, // stdout - Readable | null, // stderr - Readable | Writable | null | undefined, // extra + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra Readable | Writable | null | undefined // extra ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ readonly killed: boolean; - readonly pid: number; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ send(message: Serializable, callback?: (error: Error | null) => void): boolean; send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ ref(): void; - /** * events.EventEmitter * 1. close @@ -44,71 +520,68 @@ declare module 'child_process' { * 3. error * 4. exit * 5. message + * 6. spawn */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - + addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: 'spawn', listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; - emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; - + emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean; + emit(event: 'spawn', listener: () => void): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - + on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: 'spawn', listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - + once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: 'spawn', listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - + prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: 'spawn', listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'spawn', listener: () => void): this; } - // return this object when stdio option is undefined or not specified interface ChildProcessWithoutNullStreams extends ChildProcess { stdin: Writable; stdout: Readable; stderr: Readable; readonly stdio: [ - Writable, // stdin - Readable, // stdout - Readable, // stderr - Readable | Writable | null | undefined, // extra, no modification + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification Readable | Writable | null | undefined // extra, no modification ]; } - // return this object when stdio option is a tuple of 3 - interface ChildProcessByStdio< - I extends null | Writable, - O extends null | Readable, - E extends null | Readable, - > extends ChildProcess { + interface ChildProcessByStdio extends ChildProcess { stdin: I; stdout: O; stderr: E; @@ -116,37 +589,42 @@ declare module 'child_process' { I, O, E, - Readable | Writable | null | undefined, // extra, no modification + Readable | Writable | null | undefined, + // extra, no modification Readable | Writable | null | undefined // extra, no modification ]; } - interface MessageOptions { keepOpen?: boolean | undefined; } - - type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | Stream | number | null | undefined)>; - + type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; + type StdioOptions = IOType | Array; type SerializationType = 'json' | 'advanced'; - - interface MessagingOptions { + interface MessagingOptions extends Abortable { /** * Specify the kind of serialization used for sending messages between processes. * @default 'json' */ serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; } - interface ProcessEnvOptions { uid?: number | undefined; gid?: number | undefined; - cwd?: string | undefined; + cwd?: string | URL | undefined; env?: NodeJS.ProcessEnv | undefined; } - interface CommonOptions extends ProcessEnvOptions { /** - * @default true + * @default false */ windowsHide?: boolean | undefined; /** @@ -154,183 +632,348 @@ declare module 'child_process' { */ timeout?: number | undefined; } - - interface CommonSpawnOptions extends CommonOptions, MessagingOptions { + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { argv0?: string | undefined; stdio?: StdioOptions | undefined; shell?: boolean | string | undefined; windowsVerbatimArguments?: boolean | undefined; } - interface SpawnOptions extends CommonSpawnOptions { detached?: boolean | undefined; } - interface SpawnOptionsWithoutStdio extends SpawnOptions { - stdio?: 'pipe' | Array | undefined; + stdio?: StdioPipeNamed | StdioPipe[] | undefined; } - type StdioNull = 'inherit' | 'ignore' | Stream; - type StdioPipe = undefined | null | 'pipe'; - - interface SpawnOptionsWithStdioTuple< - Stdin extends StdioNull | StdioPipe, - Stdout extends StdioNull | StdioPipe, - Stderr extends StdioNull | StdioPipe, - > extends SpawnOptions { + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple extends SpawnOptions { stdio: [Stdin, Stdout, Stderr]; } - - // overloads of spawn without 'args' + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; - - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; function spawn(command: string, options: SpawnOptions): ChildProcess; - // overloads of spawn with 'args' function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; - - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; - interface ExecOptions extends CommonOptions { shell?: string | undefined; + signal?: AbortSignal | undefined; maxBuffer?: number | undefined; killSignal?: NodeJS.Signals | number | undefined; } - interface ExecOptionsWithStringEncoding extends ExecOptions { encoding: BufferEncoding; } - interface ExecOptionsWithBufferEncoding extends ExecOptions { encoding: BufferEncoding | null; // specify `null`. } - interface ExecException extends Error { cmd?: string | undefined; killed?: boolean | undefined; code?: number | undefined; signal?: NodeJS.Signals | undefined; } - - // no `options` definitely means stdout/stderr are `string`. + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - + function exec( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void + ): ChildProcess; // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. function exec( command: string, - options: { encoding: BufferEncoding } & ExecOptions, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void ): ChildProcess; - // `options` without an `encoding` means stdout/stderr are definitely `string`. function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - // fallback if nothing else matches. Worst case is always `string | Buffer`. function exec( command: string, - options: (BaseEncodingOptions & ExecOptions) | undefined | null, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void ): ChildProcess; - interface PromiseWithChild extends Promise { child: ChildProcess; } - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. namespace exec { - function __promisify__(command: string): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options?: (BaseEncodingOptions & ExecOptions) | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; } - - interface ExecFileOptions extends CommonOptions { + interface ExecFileOptions extends CommonOptions, Abortable { maxBuffer?: number | undefined; killSignal?: NodeJS.Signals | number | undefined; windowsVerbatimArguments?: boolean | undefined; shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; } interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { encoding: BufferEncoding; @@ -342,48 +985,101 @@ declare module 'child_process' { encoding: BufferEncoding; } type ExecFileException = ExecException & NodeJS.ErrnoException; - + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ function execFile(file: string): ChildProcess; - function execFile(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; - function execFile(file: string, args: ReadonlyArray | undefined | null, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; - + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; // no `options` definitely means stdout/stderr are `string`. function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; function execFile( file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithBufferEncoding, - callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void ): ChildProcess; - // `options` with well known `encoding` means stdout/stderr are definitely `string`. function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; function execFile( file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void ): ChildProcess; - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function execFile( - file: string, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; + function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; function execFile( file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void ): ChildProcess; - // `options` without an `encoding` means stdout/stderr are definitely `string`. function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; function execFile( @@ -392,45 +1088,107 @@ declare module 'child_process' { options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void ): ChildProcess; - // fallback if nothing else matches. Worst case is always `string | Buffer`. function execFile( file: string, - options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, - callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null ): ChildProcess; function execFile( file: string, args: ReadonlyArray | undefined | null, - options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, - callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null ): ChildProcess; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. namespace execFile { - function __promisify__(file: string): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; function __promisify__( file: string, args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - ): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__(file: string, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; function __promisify__( file: string, args: ReadonlyArray | undefined | null, - options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, - ): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; } - - interface ForkOptions extends ProcessEnvOptions, MessagingOptions { + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { execPath?: string | undefined; execArgv?: string[] | undefined; silent?: boolean | undefined; @@ -438,12 +1196,59 @@ declare module 'child_process' { detached?: boolean | undefined; windowsVerbatimArguments?: boolean | undefined; } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ function fork(modulePath: string, options?: ForkOptions): ChildProcess; function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; - interface SpawnSyncOptions extends CommonSpawnOptions { input?: string | NodeJS.ArrayBufferView | undefined; - killSignal?: NodeJS.Signals | number | undefined; maxBuffer?: number | undefined; encoding?: BufferEncoding | 'buffer' | null | undefined; } @@ -462,55 +1267,102 @@ declare module 'child_process' { signal: NodeJS.Signals | null; error?: Error | undefined; } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ function spawnSync(command: string): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args: ReadonlyArray, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; - - interface ExecSyncOptions extends CommonOptions { - input?: string | Uint8Array | undefined; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; stdio?: StdioOptions | undefined; - shell?: string | undefined; killSignal?: NodeJS.Signals | number | undefined; maxBuffer?: number | undefined; encoding?: BufferEncoding | 'buffer' | null | undefined; } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { encoding: BufferEncoding; } interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { encoding?: 'buffer' | null | undefined; } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ function execSync(command: string): Buffer; function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; function execSync(command: string, options?: ExecSyncOptions): string | Buffer; - - interface ExecFileSyncOptions extends CommonOptions { - input?: string | NodeJS.ArrayBufferView | undefined; - stdio?: StdioOptions | undefined; - killSignal?: NodeJS.Signals | number | undefined; - maxBuffer?: number | undefined; - encoding?: BufferEncoding | undefined; + interface ExecFileSyncOptions extends CommonExecOptions { shell?: boolean | string | undefined; } interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { encoding: BufferEncoding; } interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; // specify `null`. + encoding?: 'buffer' | null; // specify `null`. } - function execFileSync(command: string): Buffer; - function execFileSync(command: string, options: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(command: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(command: string, options?: ExecFileSyncOptions): string | Buffer; - function execFileSync(command: string, args: ReadonlyArray): Buffer; - function execFileSync(command: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(command: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): string | Buffer; + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: ReadonlyArray): Buffer; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args: ReadonlyArray, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): string | Buffer; } declare module 'node:child_process' { export * from 'child_process'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/cluster.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/cluster.d.ts index c2c7cd435..335275948 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/cluster.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/cluster.d.ts @@ -1,13 +1,64 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * A single instance of Node.js runs in a single thread. To take advantage of + * multi-core systems, the user will sometimes want to launch a cluster of Node.js + * processes to handle the load. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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/v16.9.0/lib/cluster.js) + */ declare module 'cluster' { - import * as child from 'child_process'; - import EventEmitter = require('events'); - import * as net from 'net'; - - // interfaces - interface ClusterSettings { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { execArgv?: string[] | undefined; // default: process.execArgv exec?: string | undefined; args?: string[] | undefined; @@ -17,24 +68,214 @@ declare module 'cluster' { gid?: number | undefined; inspectPort?: number | (() => number) | 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 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, it does this + * by disconnecting the `worker.process`, and once disconnected, killing + * with `signal`. In the worker, it does it by disconnecting the channel, + * and then exiting with code `0`. + * + * Because `kill()` attempts to gracefully disconnect the worker process, it is + * susceptible to waiting indefinitely for the disconnect to complete. For example, + * if the worker enters an infinite loop, a graceful disconnect will never occur. + * If the graceful disconnect behavior is not needed, use `worker.process.kill()`. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * This method is aliased as `worker.destroy()` for backward 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('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 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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 `.kill()` or`.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; - /** * events.EventEmitter * 1. disconnect @@ -45,69 +286,67 @@ declare module 'cluster' { * 6. online */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - 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: "online", listener: () => void): this; - + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'exit', listener: (code: number, signal: string) => void): this; + 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: 'online', listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "listening", address: Address): boolean; - emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online"): boolean; - + emit(event: 'disconnect'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'exit', code: number, signal: string): boolean; + emit(event: 'listening', address: Address): boolean; + emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online'): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => 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: "online", listener: () => void): this; - + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'exit', listener: (code: number, signal: string) => 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: 'online', listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => 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: "online", listener: () => void): this; - + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'exit', listener: (code: number, signal: string) => 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: 'online', listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => 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: "online", listener: () => void): this; - + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'exit', listener: (code: number, signal: string) => 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: 'online', listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => 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: "online", listener: () => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number, signal: string) => 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: 'online', listener: () => void): this; } - - interface Cluster extends 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 | undefined; - workers?: NodeJS.Dict | undefined; - + /** + * `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 | undefined; readonly SCHED_NONE: number; readonly SCHED_RR: number; - /** * events.EventEmitter * 1. disconnect @@ -119,150 +358,60 @@ declare module 'cluster' { * 7. setup */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - 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: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - + addListener(event: 'disconnect', listener: (worker: Worker) => void): this; + addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: 'fork', listener: (worker: Worker) => void): this; + 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: 'online', listener: (worker: Worker) => void): this; + addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect", worker: Worker): boolean; - emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - emit(event: "fork", worker: Worker): boolean; - emit(event: "listening", worker: Worker, address: Address): boolean; - emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online", worker: Worker): boolean; - emit(event: "setup", settings: ClusterSettings): boolean; - + emit(event: 'disconnect', worker: Worker): boolean; + emit(event: 'exit', worker: Worker, code: number, signal: string): boolean; + emit(event: 'fork', worker: Worker): boolean; + emit(event: 'listening', worker: Worker, address: Address): boolean; + emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online', worker: Worker): boolean; + emit(event: 'setup', settings: ClusterSettings): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", 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: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: ClusterSettings) => void): this; - + on(event: 'disconnect', listener: (worker: Worker) => void): this; + on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: 'fork', 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: 'online', listener: (worker: Worker) => void): this; + on(event: 'setup', listener: (settings: ClusterSettings) => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", 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: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: ClusterSettings) => void): this; - + once(event: 'disconnect', listener: (worker: Worker) => void): this; + once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: 'fork', 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: 'online', listener: (worker: Worker) => void): this; + once(event: 'setup', listener: (settings: ClusterSettings) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", 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. - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: 'fork', listener: (worker: Worker) => void): this; + prependListener(event: 'listening', listener: (worker: Worker, address: Address) => 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: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + 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; + prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => 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: '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; - - /** - * 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'; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/console.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/console.d.ts index f89ecaa57..7dae84bd4 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/console.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/console.d.ts @@ -1,100 +1,321 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * 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.9.0/lib/console.js) + */ declare module 'console' { import console = require('node:console'); export = console; } declare module 'node:console' { - import { InspectOptions } from 'util'; - + 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 The display label for the counter. */ 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 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): 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 */ 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('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 */ 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 */ 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. (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 --- /** * This method does not display anything unless used in the inspector. @@ -112,13 +333,67 @@ declare module 'node:console' { */ timeStamp(label?: string): void; } - - 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 | undefined; + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; ignoreErrors?: boolean | undefined; colorMode?: boolean | 'auto' | undefined; inspectOptions?: InspectOptions | undefined; @@ -126,20 +401,15 @@ declare module 'node:console' { * Set group indentation * @default 2 */ - groupIndentation?: number | undefined; + groupIndentation?: number | undefined; } - interface ConsoleConstructor { prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface Global { - console: typeof console; + new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new (options: ConsoleConstructorOptions): Console; } } + var console: Console; } - - export = console; + export = globalThis.console; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/crypto.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/crypto.d.ts index 4085825c6..027b7d750 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/crypto.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/crypto.d.ts @@ -1,10 +1,55 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/crypto.js) + */ declare module 'crypto' { - import * as stream from 'stream'; - + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; interface Certificate { + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + const Certificate: Certificate & { + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + new (): Certificate; + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + (): Certificate; /** * @param spkac * @returns The challenge component of the `spkac` data structure, @@ -24,18 +69,10 @@ declare module 'crypto' { * `false` otherwise. */ verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; - } - const Certificate: Certificate & { - /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ - new (): Certificate; - /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ - (): Certificate; }; - namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants const OPENSSL_VERSION_NUMBER: number; - /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ const SSL_OP_ALL: number; /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ @@ -85,7 +122,6 @@ declare module 'crypto' { const SSL_OP_TLS_D5_BUG: number; /** Instructs OpenSSL to disable version rollback attack detection. */ const SSL_OP_TLS_ROLLBACK_BUG: number; - const ENGINE_METHOD_RSA: number; const ENGINE_METHOD_DSA: number; const ENGINE_METHOD_DH: number; @@ -97,14 +133,11 @@ declare module 'crypto' { const ENGINE_METHOD_PKEY_ASN1_METHS: number; const ENGINE_METHOD_ALL: number; const ENGINE_METHOD_NONE: number; - const DH_CHECK_P_NOT_SAFE_PRIME: number; const DH_CHECK_P_NOT_PRIME: number; const DH_UNABLE_TO_CHECK_GENERATOR: number; const DH_NOT_SUITABLE_GENERATOR: number; - const ALPN_ENABLED: number; - const RSA_PKCS1_PADDING: number; const RSA_SSLV23_PADDING: number; const RSA_NO_PADDING: number; @@ -117,17 +150,14 @@ declare module 'crypto' { const RSA_PSS_SALTLEN_MAX_SIGN: number; /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ const RSA_PSS_SALTLEN_AUTO: number; - const POINT_CONVERSION_COMPRESSED: number; const POINT_CONVERSION_UNCOMPRESSED: number; const POINT_CONVERSION_HYBRID: number; - /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ const defaultCoreCipherList: string; /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ const defaultCipherList: string; } - interface HashOptions extends stream.TransformOptions { /** * For XOF hash functions such as `shake256`, the @@ -135,188 +165,1104 @@ declare module 'crypto' { */ outputLength?: number | undefined; } - /** @deprecated since v10.0.0 */ const fips: boolean; - + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; - // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex'; type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; - type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; - type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; - + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ class Hash extends stream.Transform { private constructor(); - copy(): Hash; + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ update(data: BinaryLike): Hash; - update(data: string, input_encoding: Encoding): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ digest(): Buffer; digest(encoding: BinaryToTextEncoding): string; } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ class Hmac extends stream.Transform { private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ update(data: BinaryLike): Hmac; - update(data: string, input_encoding: Encoding): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ digest(): Buffer; digest(encoding: BinaryToTextEncoding): string; } - type KeyObjectType = 'secret' | 'public' | 'private'; - interface KeyExportOptions { type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; format: T; cipher?: string | undefined; passphrase?: string | Buffer | undefined; } - + interface JwkKeyExportOptions { + format: 'jwk'; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ class KeyObject { private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256 + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ asymmetricKeyType?: KeyType | undefined; /** * For asymmetric keys, this property represents the size of the embedded key in * bytes. This property is `undefined` for symmetric keys. */ asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ export(options: KeyExportOptions<'pem'>): string | Buffer; export(options?: KeyExportOptions<'der'>): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ type: KeyObjectType; } - type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; - + type CipherOCBTypes = 'aes-128-ocb' | 'aes-192-ocb' | 'aes-256-ocb'; type BinaryLike = string | NodeJS.ArrayBufferView; - type CipherKey = BinaryLike | KeyObject; - interface CipherCCMOptions extends stream.TransformOptions { authTagLength: number; } interface CipherGCMOptions extends stream.TransformOptions { authTagLength?: number | undefined; } - /** @deprecated since v10.0.0 use `createCipheriv()` */ + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; /** @deprecated since v10.0.0 use `createCipheriv()` */ function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; /** @deprecated since v10.0.0 use `createCipheriv()` */ function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; - - function createCipheriv( - algorithm: CipherCCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options: CipherCCMOptions, - ): CipherCCM; - function createCipheriv( - algorithm: CipherGCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options?: CipherGCMOptions, - ): CipherGCM; - function createCipheriv( - algorithm: string, - key: CipherKey, - iv: BinaryLike | null, - options?: stream.TransformOptions, - ): Cipher; - + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): CipherOCB; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ class Cipher extends stream.Transform { private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ update(data: BinaryLike): Buffer; - update(data: string, input_encoding: Encoding): Buffer; - update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string; - update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ final(): Buffer; - final(output_encoding: BufferEncoding): string; - setAutoPadding(auto_padding?: boolean): this; - // getAuthTag(): Buffer; - // setAAD(buffer: NodeJS.ArrayBufferView): this; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; } interface CipherCCM extends Cipher { - setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; getAuthTag(): Buffer; } interface CipherGCM extends Cipher { - setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; getAuthTag(): Buffer; } - /** @deprecated since v10.0.0 use `createDecipheriv()` */ + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; /** @deprecated since v10.0.0 use `createDecipheriv()` */ function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; /** @deprecated since v10.0.0 use `createDecipheriv()` */ function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; - - function createDecipheriv( - algorithm: CipherCCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options: CipherCCMOptions, - ): DecipherCCM; - function createDecipheriv( - algorithm: CipherGCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options?: CipherGCMOptions, - ): DecipherGCM; - function createDecipheriv( - algorithm: string, - key: CipherKey, - iv: BinaryLike | null, - options?: stream.TransformOptions, - ): Decipher; - + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): DecipherOCB; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ class Decipher extends stream.Transform { private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ update(data: NodeJS.ArrayBufferView): Buffer; - update(data: string, input_encoding: Encoding): Buffer; - update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string; - update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ final(): Buffer; - final(output_encoding: BufferEncoding): string; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ setAutoPadding(auto_padding?: boolean): this; - // setAuthTag(tag: NodeJS.ArrayBufferView): this; - // setAAD(buffer: NodeJS.ArrayBufferView): this; } interface DecipherCCM extends Decipher { setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; } interface DecipherGCM extends Decipher { setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; } - interface PrivateKeyInput { key: string | Buffer; format?: KeyFormat | undefined; type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; passphrase?: string | Buffer | undefined; + encoding?: string | undefined; } - interface PublicKeyInput { key: string | Buffer; format?: KeyFormat | undefined; type?: 'pkcs1' | 'spki' | undefined; + encoding?: string | undefined; } - - function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; - function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject; + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: 'hmac' | 'aes', + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync + * } = await import('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: 'hmac' | 'aes', + options: { + length: number; + } + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: 'jwk'; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; - - function createSign(algorithm: string, options?: stream.WritableOptions): Signer; - + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; type DSAEncoding = 'der' | 'ieee-p1363'; - interface SigningOptions { /** * @See crypto.constants.RSA_PKCS1_PADDING @@ -325,7 +1271,6 @@ declare module 'crypto' { saltLength?: number | undefined; dsaEncoding?: DSAEncoding | undefined; } - interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} interface SignKeyObjectInput extends SigningOptions { key: KeyObject; @@ -334,137 +1279,697 @@ declare module 'crypto' { interface VerifyKeyObjectInput extends SigningOptions { key: KeyObject; } - type KeyLike = string | Buffer | KeyObject; - - class Signer extends stream.Writable { + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { private constructor(); - - update(data: BinaryLike): Signer; - update(data: string, input_encoding: Encoding): Signer; - sign(private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; - sign( - private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - output_format: BinaryToTextEncoding, - ): string; + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string; } - + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ class Verify extends stream.Writable { private constructor(); - + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ update(data: BinaryLike): Verify; - update(data: string, input_encoding: Encoding): Verify; - verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, - signature: NodeJS.ArrayBufferView, - ): boolean; - verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, - signature: string, - signature_format?: BinaryToTextEncoding, - ): boolean; - // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format - // The signature field accepts a TypedArray type, but it is only available starting ES2017 + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; } - function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: BinaryToTextEncoding): DiffieHellman; - function createDiffieHellman( - prime: string, - prime_encoding: BinaryToTextEncoding, - generator: number | NodeJS.ArrayBufferView, - ): DiffieHellman; - function createDiffieHellman( - prime: string, - prime_encoding: BinaryToTextEncoding, - generator: string, - generator_encoding: BinaryToTextEncoding, - ): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ class DiffieHellman { private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ generateKeys(): Buffer; generateKeys(encoding: BinaryToTextEncoding): string; - computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; - computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer; - computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string; - computeSecret( - other_public_key: string, - input_encoding: BinaryToTextEncoding, - output_encoding: BinaryToTextEncoding, - ): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding: null, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ getPrime(): Buffer; getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ getGenerator(): Buffer; getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ getPublicKey(): Buffer; getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ getPrivateKey(): Buffer; getPrivateKey(encoding: BinaryToTextEncoding): string; - setPublicKey(public_key: NodeJS.ArrayBufferView): void; - setPublicKey(public_key: string, encoding: BufferEncoding): void; - setPrivateKey(private_key: NodeJS.ArrayBufferView): void; - setPrivateKey(private_key: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ verifyError: number; } - function getDiffieHellman(group_name: string): DiffieHellman; - function pbkdf2( - password: BinaryLike, - salt: BinaryLike, - iterations: number, - keylen: number, - digest: string, - callback: (err: Error | null, derivedKey: Buffer) => any, - ): void; - function pbkdf2Sync( - password: BinaryLike, - salt: BinaryLike, - iterations: number, - keylen: number, - digest: string, - ): Buffer; - + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ function randomBytes(size: number): Buffer; function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; function pseudoRandomBytes(size: number): Buffer; function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than `2**48`. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ function randomInt(max: number): number; function randomInt(min: number, max: number): number; function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; - + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ function randomFillSync(buffer: T, offset?: number, size?: number): T; - function randomFill( - buffer: T, - callback: (err: Error | null, buf: T) => void, - ): void; - function randomFill( - buffer: T, - offset: number, - callback: (err: Error | null, buf: T) => void, - ): void; - function randomFill( - buffer: T, - offset: number, - size: number, - callback: (err: Error | null, buf: T) => void, - ): void; - - interface RandomUUIDOptions { - /** - * By default, to improve performance, - * Node.js will pre-emptively generate and persistently cache enough - * random data to generate up to 128 random UUIDs. To generate a UUID - * without using the cache, set `disableEntropyCache` to `true`. - * - * @default `false` - */ - disableEntropyCache?: boolean | undefined; - } - - function randomUUID(options?: RandomUUIDOptions): string; - + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; interface ScryptOptions { cost?: number | undefined; blockSize?: number | undefined; @@ -474,21 +1979,73 @@ declare module 'crypto' { p?: number | undefined; maxmem?: number | undefined; } - function scrypt( - password: BinaryLike, - salt: BinaryLike, - keylen: number, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - function scrypt( - password: BinaryLike, - salt: BinaryLike, - keylen: number, - options: ScryptOptions, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; - interface RsaPublicKey { key: KeyLike; padding?: number | undefined; @@ -503,124 +2060,350 @@ declare module 'crypto' { oaepLabel?: NodeJS.TypedArray | undefined; padding?: number | undefined; } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ class ECDH { private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ static convertKey( key: BinaryLike, curve: string, inputEncoding?: BinaryToTextEncoding, outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url', - format?: 'uncompressed' | 'compressed' | 'hybrid', + format?: 'uncompressed' | 'compressed' | 'hybrid' ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ generateKeys(): Buffer; generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; - computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; - computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer; - computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string; - computeSecret( - other_public_key: string, - input_encoding: BinaryToTextEncoding, - output_encoding: BinaryToTextEncoding, - ): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ getPrivateKey(): Buffer; getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ getPublicKey(): Buffer; getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; - setPrivateKey(private_key: NodeJS.ArrayBufferView): void; - setPrivateKey(private_key: string, encoding: BinaryToTextEncoding): void; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; } - function createECDH(curve_name: string): ECDH; + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; /** @deprecated since v10.0.0 */ const DEFAULT_ENCODING: BufferEncoding; - - type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; - type KeyFormat = 'pem' | 'der'; - + type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der' | 'jwk'; interface BasePrivateKeyEncodingOptions { format: T; cipher?: string | undefined; passphrase?: string | undefined; } - interface KeyPairKeyObjectResult { publicKey: KeyObject; privateKey: KeyObject; } - - interface ED25519KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface ED448KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface X25519KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface X448KeyPairKeyObjectOptions { - /** - * No options. - */ - } - + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} interface ECKeyPairKeyObjectOptions { /** - * Name of the curve to use. + * Name of the curve to use */ namedCurve: string; } - interface RSAKeyPairKeyObjectOptions { /** * Key size in bits */ modulusLength: number; - /** + * Public exponent * @default 0x10001 */ publicExponent?: number | undefined; } - + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } interface DSAKeyPairKeyObjectOptions { /** * Key size in bits */ modulusLength: number; - /** * Size of q in bits */ divisorLength: number; } - interface RSAKeyPairOptions { /** * Key size in bits */ modulusLength: number; /** + * Public exponent * @default 0x10001 */ publicExponent?: number | undefined; - publicKeyEncoding: { type: 'pkcs1' | 'spki'; format: PubF; @@ -629,7 +2412,36 @@ declare module 'crypto' { type: 'pkcs1' | 'pkcs8'; }; } - + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } interface DSAKeyPairOptions { /** * Key size in bits @@ -639,7 +2451,6 @@ declare module 'crypto' { * Size of q in bits */ divisorLength: number; - publicKeyEncoding: { type: 'spki'; format: PubF; @@ -648,13 +2459,11 @@ declare module 'crypto' { type: 'pkcs8'; }; } - interface ECKeyPairOptions { /** * Name of the curve to use. */ namedCurve: string; - publicKeyEncoding: { type: 'pkcs1' | 'spki'; format: PubF; @@ -663,7 +2472,6 @@ declare module 'crypto' { type: 'sec1' | 'pkcs8'; }; } - interface ED25519KeyPairOptions { publicKeyEncoding: { type: 'spki'; @@ -673,7 +2481,6 @@ declare module 'crypto' { type: 'pkcs8'; }; } - interface ED448KeyPairOptions { publicKeyEncoding: { type: 'spki'; @@ -683,7 +2490,6 @@ declare module 'crypto' { type: 'pkcs8'; }; } - interface X25519KeyPairOptions { publicKeyEncoding: { type: 'spki'; @@ -693,7 +2499,6 @@ declare module 'crypto' { type: 'pkcs8'; }; } - interface X448KeyPairOptions { publicKeyEncoding: { type: 'spki'; @@ -703,489 +2508,1357 @@ declare module 'crypto' { type: 'pkcs8'; }; } - interface KeyPairSyncResult { publicKey: T1; privateKey: T2; } - - function generateKeyPairSync( - type: 'rsa', - options: RSAKeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'rsa', - options: RSAKeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'rsa', - options: RSAKeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'rsa', - options: RSAKeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync( - type: 'dsa', - options: DSAKeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'dsa', - options: DSAKeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'dsa', - options: DSAKeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'dsa', - options: DSAKeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync( - type: 'ec', - options: ECKeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ec', - options: ECKeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ec', - options: ECKeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ec', - options: ECKeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync( - type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync( - type: 'ed448', - options: ED448KeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ed448', - options: ED448KeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ed448', - options: ED448KeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'ed448', - options: ED448KeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync( - type: 'x25519', - options: X25519KeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'x25519', - options: X25519KeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'x25519', - options: X25519KeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'x25519', - options: X25519KeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync( - type: 'x448', - options: X448KeyPairOptions<'pem', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'x448', - options: X448KeyPairOptions<'pem', 'der'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'x448', - options: X448KeyPairOptions<'der', 'pem'>, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: 'x448', - options: X448KeyPairOptions<'der', 'der'>, - ): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPair( - type: 'rsa', - options: RSAKeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'rsa', - options: RSAKeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'rsa', - options: RSAKeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'rsa', - options: RSAKeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'rsa', - options: RSAKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - - function generateKeyPair( - type: 'dsa', - options: DSAKeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'dsa', - options: DSAKeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'dsa', - options: DSAKeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'dsa', - options: DSAKeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'dsa', - options: DSAKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - - function generateKeyPair( - type: 'ec', - options: ECKeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'ec', - options: ECKeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'ec', - options: ECKeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'ec', - options: ECKeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'ec', - options: ECKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - - function generateKeyPair( - type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'ed25519', - options: ED25519KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - - function generateKeyPair( - type: 'ed448', - options: ED448KeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'ed448', - options: ED448KeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'ed448', - options: ED448KeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'ed448', - options: ED448KeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'ed448', - options: ED448KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - - function generateKeyPair( - type: 'x25519', - options: X25519KeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'x25519', - options: X25519KeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'x25519', - options: X25519KeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'x25519', - options: X25519KeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'x25519', - options: X25519KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - - function generateKeyPair( - type: 'x448', - options: X448KeyPairOptions<'pem', 'pem'>, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'x448', - options: X448KeyPairOptions<'pem', 'der'>, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'x448', - options: X448KeyPairOptions<'der', 'pem'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: 'x448', - options: X448KeyPairOptions<'der', 'der'>, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: 'x448', - options: X448KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; namespace generateKeyPair { function __promisify__( type: 'rsa', - options: RSAKeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: RSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'rsa', - options: RSAKeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: RSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'rsa', - options: RSAKeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: RSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'rsa', - options: RSAKeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + options: RSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; - + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa-pss', + options: RSAPSSKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise; function __promisify__( type: 'dsa', - options: DSAKeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: DSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'dsa', - options: DSAKeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: DSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'dsa', - options: DSAKeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: DSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'dsa', - options: DSAKeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + options: DSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; - function __promisify__( type: 'ec', - options: ECKeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: ECKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'ec', - options: ECKeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: ECKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'ec', - options: ECKeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: ECKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'ec', - options: ECKeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + options: ECKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; - function __promisify__( type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: ED25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'ed25519', - options: ED25519KeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: ED25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: ED25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'ed25519', - options: ED25519KeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; - function __promisify__( - type: 'ed25519', - options?: ED25519KeyPairKeyObjectOptions, - ): Promise; - + options: ED25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise; function __promisify__( type: 'ed448', - options: ED448KeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: ED448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'ed448', - options: ED448KeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: ED448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'ed448', - options: ED448KeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: ED448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'ed448', - options: ED448KeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + options: ED448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; - function __promisify__( type: 'x25519', - options: X25519KeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: X25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'x25519', - options: X25519KeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: X25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'x25519', - options: X25519KeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: X25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'x25519', - options: X25519KeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; - function __promisify__( - type: 'x25519', - options?: X25519KeyPairKeyObjectOptions, - ): Promise; - + options: X25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise; function __promisify__( type: 'x448', - options: X448KeyPairOptions<'pem', 'pem'>, - ): Promise<{ publicKey: string; privateKey: string }>; + options: X448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; function __promisify__( type: 'x448', - options: X448KeyPairOptions<'pem', 'der'>, - ): Promise<{ publicKey: string; privateKey: Buffer }>; + options: X448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; function __promisify__( type: 'x448', - options: X448KeyPairOptions<'der', 'pem'>, - ): Promise<{ publicKey: Buffer; privateKey: string }>; + options: X448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; function __promisify__( type: 'x448', - options: X448KeyPairOptions<'der', 'der'>, - ): Promise<{ publicKey: Buffer; privateKey: Buffer }>; + options: X448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; } - /** * Calculates and returns the signature for `data` using the given private key and * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is * dependent upon the key type (especially Ed25519 and Ed448). * - * If `key` is not a [`KeyObject`][], this function behaves as if `key` had been - * passed to [`crypto.createPrivateKey()`][]. + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 */ + function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; function sign( algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - ): Buffer; - + callback: (error: Error | null, data: Buffer) => void + ): void; /** - * Calculates and returns the signature for `data` using the given private key and - * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is - * dependent upon the key type (especially Ed25519 and Ed448). + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). * - * If `key` is not a [`KeyObject`][], this function behaves as if `key` had been - * passed to [`crypto.createPublicKey()`][]. + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 */ + function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; function verify( algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView, - ): boolean; - + callback: (error: Error | null, result: boolean) => void + ): void; /** - * Computes the Diffie-Hellman secret based on a privateKey and a publicKey. - * Both keys must have the same asymmetricKeyType, which must be one of - * 'dh' (for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES). + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 */ function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: 'always' | 'default' | 'never'; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (ca) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * @since v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate or `undefined` + * if not available. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * The information access content of this certificate or `undefined` if not + * available. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * @since v15.6.0 + * @return Returns `name` if the certificate matches, `undefined` if it does not. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. + * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * - `crypto.constants.ENGINE_METHOD_RSA` + * - `crypto.constants.ENGINE_METHOD_DSA` + * - `crypto.constants.ENGINE_METHOD_DH` + * - `crypto.constants.ENGINE_METHOD_RAND` + * - `crypto.constants.ENGINE_METHOD_EC` + * - `crypto.constants.ENGINE_METHOD_CIPHERS` + * - `crypto.constants.ENGINE_METHOD_DIGESTS` + * - `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * - `crypto.constants.ENGINE_METHOD_ALL` + * - `crypto.constants.ENGINE_METHOD_NONE` + * + * The flags below are deprecated in OpenSSL-1.1.0. + * + * - `crypto.constants.ENGINE_METHOD_ECDH` + * - `crypto.constants.ENGINE_METHOD_ECDSA` + * - `crypto.constants.ENGINE_METHOD_STORE` + * @since v0.11.11 + * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + */ + function setEngine(engine: string, flags?: number): void; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = 'jwk' | 'pkcs8' | 'raw' | 'spki'; + type KeyType = 'private' | 'public' | 'secret'; + type KeyUsage = 'decrypt' | 'deriveBits' | 'deriveKey' | 'encrypt' | 'sign' | 'unwrapKey' | 'verify' | 'wrapKey'; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): string; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: 'CryptoKey'; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that `length` is a multiple of `8`. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, + extractable: boolean, + keyUsages: ReadonlyArray + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: 'jwk', key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'ECDH'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray): Promise; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray): Promise; + generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: 'jwk', + keyData: JsonWebKey, + algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: ReadonlyArray + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[] + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, data: BufferSource): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'ECDH'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[] + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise; + } + } } declare module 'node:crypto' { export * from 'crypto'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/desktop.ini b/packages/node_modules/@node-red/editor-client/src/types/node/desktop.ini new file mode 100644 index 000000000..d957fd188 --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/desktop.ini @@ -0,0 +1,4 @@ +[ViewState] +Mode= +Vid= +FolderType=Generic diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/dgram.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/dgram.d.ts index c93028a29..6f9b0ec5e 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/dgram.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/dgram.d.ts @@ -1,28 +1,51 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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/v16.9.0/lib/dgram.js) + */ declare module 'dgram' { - import { AddressInfo } from 'net'; - import * as dns from 'dns'; - import EventEmitter = require('events'); - + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } from 'node:events'; interface RemoteInfo { address: string; family: 'IPv4' | 'IPv6'; port: number; size: number; } - interface BindOptions { port?: number | undefined; address?: string | undefined; exclusive?: boolean | undefined; fd?: number | undefined; } - - type SocketType = "udp4" | "udp6"; - - interface SocketOptions { + type SocketType = 'udp4' | 'udp6'; + interface SocketOptions extends Abortable { type: SocketType; reuseAddr?: boolean | undefined; /** @@ -33,64 +56,447 @@ declare module 'dgram' { 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; - + /** + * 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 'cluster'; + * import dgram from '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; + /** + * 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 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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; + /** + * 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 falsy, `'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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; send(msg: string | Uint8Array | ReadonlyArray, 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; + /** + * 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; + /** + * 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 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 * reason to call this. * * If `multicastInterface` is not specified, the operating system will attempt to * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 */ dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; - /** * events.EventEmitter * 1. close @@ -100,46 +506,41 @@ declare module 'dgram' { * 5. message */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; - + emit(event: 'close'): boolean; + emit(event: 'connect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - + on(event: 'close', listener: () => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - + once(event: 'close', listener: () => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; } } declare module 'node:dgram' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/diagnostics_channel.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/diagnostics_channel.d.ts new file mode 100644 index 000000000..d67a7b2e5 --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/diagnostics_channel.d.ts @@ -0,0 +1,155 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will + * trigger message handlers synchronously so they will execute within + * the same context. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message' + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @param onMessage The previous subscribed handler to remove + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module 'node:diagnostics_channel' { + export * from 'diagnostics_channel'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/dns.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/dns.d.ts index b31ea02ea..65db4e843 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/dns.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/dns.d.ts @@ -1,89 +1,194 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `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('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 `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('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/v16.9.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; /** * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as * well as IPv4 mapped IPv6 addresses. */ - const ALL: number; - - interface LookupOptions { + export const ALL: number; + export interface LookupOptions { family?: number | undefined; hints?: number | undefined; all?: boolean | undefined; verbatim?: boolean | undefined; } - - interface LookupOneOptions extends LookupOptions { + 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 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('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; function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; function __promisify__(hostname: string, options: LookupOptions): Promise; } - - 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('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 { - type: "A"; + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: 'A'; } - - interface AnyAaaaRecord extends RecordWithTtl { - type: "AAAA"; + export interface AnyAaaaRecord extends RecordWithTtl { + type: 'AAAA'; } - - interface MxRecord { + export interface CaaRecord { + critial: 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 { - type: "MX"; + export interface AnyMxRecord extends MxRecord { + type: 'MX'; } - - interface NaptrRecord { + export interface NaptrRecord { flags: string; service: string; regexp: string; @@ -91,12 +196,10 @@ declare module 'dns' { order: number; preference: number; } - - interface AnyNaptrRecord extends NaptrRecord { - type: "NAPTR"; + export interface AnyNaptrRecord extends NaptrRecord { + type: 'NAPTR'; } - - interface SoaRecord { + export interface SoaRecord { nsname: string; hostmaster: string; serial: number; @@ -105,188 +208,415 @@ declare module 'dns' { expire: number; minttl: number; } - - interface AnySoaRecord extends SoaRecord { - type: "SOA"; + export interface AnySoaRecord extends SoaRecord { + type: 'SOA'; } - - interface SrvRecord { + export interface SrvRecord { priority: number; weight: number; port: number; name: string; } - - interface AnySrvRecord extends SrvRecord { - type: "SRV"; + export interface AnySrvRecord extends SrvRecord { + type: 'SRV'; } - - interface AnyTxtRecord { - type: "TXT"; + export interface AnyTxtRecord { + type: 'TXT'; entries: string[]; } - - interface AnyNsRecord { - type: "NS"; + export interface AnyNsRecord { + type: 'NS'; value: string; } - - interface AnyPtrRecord { - type: "PTR"; + export interface AnyPtrRecord { + type: 'PTR'; value: string; } - - interface AnyCnameRecord { - type: "CNAME"; + 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`: + * + * + * + * 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 { - function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; - function __promisify__(hostname: string, rrtype: "ANY"): Promise; - function __promisify__(hostname: string, rrtype: "MX"): Promise; - function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; - function __promisify__(hostname: string, rrtype: "SOA"): Promise; - function __promisify__(hostname: string, rrtype: "SRV"): Promise; - function __promisify__(hostname: string, rrtype: "TXT"): Promise; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise; + function __promisify__(hostname: string, rrtype: 'ANY'): Promise; + function __promisify__(hostname: string, rrtype: 'MX'): Promise; + function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise; + function __promisify__(hostname: string, rrtype: 'SOA'): Promise; + function __promisify__(hostname: string, rrtype: 'SRV'): Promise; + function __promisify__(hostname: string, rrtype: 'TXT'): Promise; function __promisify__(hostname: string, rrtype: string): Promise; } - - 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; function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; function __promisify__(hostname: string, options?: ResolveOptions): Promise; } - - 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 a 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; function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; function __promisify__(hostname: string, options?: ResolveOptions): Promise; } - - 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; } - - 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 + */ + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * 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; } - - 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; } - - 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; } - - 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; } - - 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; } - - 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; } - - 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; } - - 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: + * + * + * + * 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; } - - function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; - function setServers(servers: ReadonlyArray): void; - function getServers(): string[]; - - function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; - + /** + * 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; + /** + * 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: ReadonlyArray): 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}. The value could be: + * - `ipv4first`: sets default `verbatim` `false`. + * - `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` 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 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; - - interface ResolverOptions { + 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; } - - class Resolver { + /** + * 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('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 `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; getServers: typeof getServers; resolve: typeof resolve; @@ -302,88 +632,25 @@ declare module 'dns' { resolveSrv: typeof resolveSrv; resolveTxt: typeof resolveTxt; 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 + * @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; - function lookup(hostname: string, options: LookupOneOptions): Promise; - function lookup(hostname: string, options: LookupAllOptions): Promise; - function lookup(hostname: string, options: LookupOptions): Promise; - function lookup(hostname: string): Promise; - - function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>; - - function resolve(hostname: string): Promise; - function resolve(hostname: string, rrtype: "A"): Promise; - function resolve(hostname: string, rrtype: "AAAA"): Promise; - function resolve(hostname: string, rrtype: "ANY"): Promise; - function resolve(hostname: string, rrtype: "CNAME"): Promise; - function resolve(hostname: string, rrtype: "MX"): Promise; - function resolve(hostname: string, rrtype: "NAPTR"): Promise; - function resolve(hostname: string, rrtype: "NS"): Promise; - function resolve(hostname: string, rrtype: "PTR"): Promise; - function resolve(hostname: string, rrtype: "SOA"): Promise; - function resolve(hostname: string, rrtype: "SRV"): Promise; - function resolve(hostname: string, rrtype: "TXT"): Promise; - function resolve(hostname: string, rrtype: string): Promise; - - function resolve4(hostname: string): Promise; - function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; - function resolve4(hostname: string, options: ResolveOptions): Promise; - - function resolve6(hostname: string): Promise; - function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; - function resolve6(hostname: string, options: ResolveOptions): Promise; - - function resolveAny(hostname: string): Promise; - - function resolveCname(hostname: string): Promise; - - function resolveMx(hostname: string): Promise; - - function resolveNaptr(hostname: string): Promise; - - function resolveNs(hostname: string): Promise; - - function resolvePtr(hostname: string): Promise; - - function resolveSoa(hostname: string): Promise; - - function resolveSrv(hostname: string): Promise; - - function resolveTxt(hostname: string): Promise; - - function reverse(ip: string): Promise; - - function setServers(servers: ReadonlyArray): void; - - function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; - - class Resolver { - constructor(options?: ResolverOptions); - 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'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/dns/promises.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/dns/promises.d.ts new file mode 100644 index 000000000..0e051428b --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/dns/promises.d.ts @@ -0,0 +1,371 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from 'node:dns'; + /** + * 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 v10.6.0 + */ + function getServers(): string[]; + /** + * 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 not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with 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. + * + * `dnsPromises.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 `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.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; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * 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 error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: 'A'): Promise; + function resolve(hostname: string, rrtype: 'AAAA'): Promise; + function resolve(hostname: string, rrtype: 'ANY'): Promise; + function resolve(hostname: string, rrtype: 'CAA'): Promise; + function resolve(hostname: string, rrtype: 'CNAME'): Promise; + function resolve(hostname: string, rrtype: 'MX'): Promise; + function resolve(hostname: string, rrtype: 'NAPTR'): Promise; + function resolve(hostname: string, rrtype: 'NS'): Promise; + function resolve(hostname: string, rrtype: 'PTR'): Promise; + function resolve(hostname: string, rrtype: 'SOA'): Promise; + function resolve(hostname: string, rrtype: 'SRV'): Promise; + function resolve(hostname: string, rrtype: 'TXT'): Promise; + function resolve(hostname: string, rrtype: string): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with 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: + * + * + * + * Here is an example of the result object: + * + * ```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 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * 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 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with 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 v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with 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 v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * 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 + * dnsPromises.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 `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * 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 v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: ReadonlyArray): void; + /** + * Set the default value of `verbatim` in {@link lookup}. The value could be: + * - `ipv4first`: sets default `verbatim` `false`. + * - `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` 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 v14.18.0 + * @param order must be 'ipv4first' or 'verbatim'. + */ + function setDefaultResultOrder(order: 'ipv4first' | 'verbatim'): void; + class Resolver { + constructor(options?: ResolverOptions); + 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; + } +} +declare module 'node:dns/promises' { + export * from 'dns/promises'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/domain.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/domain.d.ts index 26ca6e26f..ad9944fca 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/domain.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/domain.d.ts @@ -1,28 +1,171 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * **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/v16.9.0/lib/domain.js) + */ declare module 'domain' { - import EventEmitter = require('events'); - - global { - namespace NodeJS { - interface Domain extends EventEmitter { - run(fn: (...args: any[]) => T, ...args: any[]): T; - add(emitter: EventEmitter | Timer): void; - remove(emitter: EventEmitter | Timer): void; - bind(cb: T): T; - intercept(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; + /** + * 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 lowlevel 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('domain'); + * const fs = require('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(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(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(callback: T): T; } - function create(): Domain; } declare module 'node:domain' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/events.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/events.d.ts index e251d6ce9..f08b20424 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/events.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/events.d.ts @@ -1,6 +1,42 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * 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 + * const EventEmitter = require('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/v16.9.0/lib/events.js) + */ declare module 'events' { interface EventEmitterOptions { /** @@ -8,26 +44,243 @@ declare module 'events' { */ captureRejections?: boolean | undefined; } - interface NodeEventTarget { - once(event: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: string | symbol, listener: (...args: any[]) => void): this; } - interface DOMEventTarget { - addEventListener(event: string, listener: (...args: any[]) => void, opts?: { once: boolean }): any; + 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 `events` module: + * + * ```js + * const EventEmitter = require('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); - - static once(emitter: NodeEventTarget, event: string | symbol): Promise; - static once(emitter: DOMEventTarget, event: string): Promise; - static on(emitter: NodeJS.EventEmitter, event: string): AsyncIterableIterator; - - /** @deprecated since v4.0.0 */ - static listenerCount(emitter: NodeJS.EventEmitter, event: string | symbol): number; - + /** + * 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. + * + * 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 + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * 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.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * 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 + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('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; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (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')) { + * // 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 + * const { on, EventEmitter } = require('events'); + * 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; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('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 + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0 + */ + static getEventListeners(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('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): 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 @@ -39,7 +292,6 @@ declare module 'events' { */ static readonly errorMonitor: unique symbol; static readonly captureRejectionSymbol: unique symbol; - /** * Sets or gets the default captureRejection value for all emitters. */ @@ -47,36 +299,343 @@ declare module 'events' { static captureRejections: boolean; static defaultMaxListeners: number; } - - import internal = require('events'); + 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; + } } - 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; + /** + * 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 + * 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 + * 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 + * 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 + * 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 + * 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 + * const EventEmitter = require('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 to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): 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 + * const EventEmitter = require('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; } } } - export = EventEmitter; } declare module 'node:events' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/fs.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/fs.d.ts index a54b19a11..f82cba2a6 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/fs.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/fs.d.ts @@ -1,30 +1,50 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/fs.js) + */ declare module 'fs' { - import * as stream from 'stream'; - import EventEmitter = require('events'); - import { URL } from 'url'; - import * as promises from 'fs/promises'; - + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import { URL } from 'node:url'; + import * as promises from 'node:fs/promises'; export { promises }; /** * Valid types for path values in "fs". */ export type PathLike = string | Buffer | URL; - + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; - - export type BufferEncodingOption = 'buffer' | { encoding: 'buffer' }; - - export interface BaseEncodingOptions { + export type BufferEncodingOption = + | 'buffer' + | { + encoding: 'buffer'; + }; + export interface ObjectEncodingOptions { encoding?: BufferEncoding | null | undefined; } - + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; export type OpenMode = number | string; - export type Mode = number | string; - export interface StatsBase { isFile(): boolean; isDirectory(): boolean; @@ -33,7 +53,6 @@ declare module 'fs' { isSymbolicLink(): boolean; isFIFO(): boolean; isSocket(): boolean; - dev: T; ino: T; mode: T; @@ -53,239 +72,437 @@ declare module 'fs' { ctime: Date; birthtime: Date; } - - export interface Stats extends StatsBase { - } - - export class Stats { - } - + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ name: string; } - /** * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from '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 */ - export class Dir { + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ readonly path: string; - /** * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. */ [Symbol.asyncIterator](): AsyncIterableIterator; - /** * Asynchronously close the directory's underlying resource handle. * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 */ close(): Promise; close(cb: NoParamCallback): void; - /** * Synchronously close the directory's underlying resource handle. * Subsequent reads will result in errors. + * @since v12.12.0 */ closeSync(): void; - /** - * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. - * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be resolved with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} */ read(): Promise; read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; - /** - * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. - * If there are no more directory entries to read, null will be returned. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 */ readSync(): Dirent | null; } - + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * @since v14.3.0, v12.20.0 + * When called, requests that the Node.js event loop not exit so long as the `fs.StatWatcher` is active. + * Calling `watcher.ref()` multiple times will have no effect. + * By default, all `fs.StatWatcher`` objects are "ref'ed", making it normally unnecessary to call `watcher.ref()` + * unless `watcher.unref()` had been called previously. + */ + ref(): this; + /** + * @since v14.3.0, v12.20.0 + * When called, the active `fs.StatWatcher`` 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 `fs.StatWatcher`` object's callback is invoked. + * `Calling watcher.unref()` multiple times will have no effect. + */ + unref(): this; + } export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ close(): void; - /** * events.EventEmitter * 1. change * 2. error */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "close", listener: () => void): this; - + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "close", listener: () => void): this; - + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "close", listener: () => void): this; - + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "close", listener: () => void): this; - + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; } - + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ export class ReadStream extends stream.Readable { close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ pending: boolean; - /** * events.EventEmitter * 1. open * 2. close * 3. ready */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "ready", listener: () => void): this; - on(event: "resume", listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'resume', listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "ready", listener: () => void): this; - once(event: "resume", listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'resume', listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - - export class WriteStream extends stream.Writable { - close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; - bytesWritten: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "ready", listener: () => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "ready", listener: () => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * 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_. + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 */ export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace rename { /** * Asynchronous rename(2) - Change the name or location of a file or directory. @@ -296,31 +513,40 @@ declare module 'fs' { */ function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; } - /** - * Synchronous 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_. + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 */ export function renameSync(oldPath: PathLike, newPath: PathLike): 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 the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] */ export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; - /** * Asynchronous truncate(2) - Truncate a file to a specified length. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. */ export function truncate(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace truncate { /** * Asynchronous truncate(2) - Truncate a file to a specified length. @@ -329,28 +555,65 @@ declare module 'fs' { */ function __promisify__(path: PathLike, len?: number | null): Promise; } - /** - * Synchronous 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 the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] */ export function truncateSync(path: PathLike, len?: number | null): void; - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * 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 v0.8.6 + * @param [len=0] */ export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; - /** * Asynchronous ftruncate(2) - Truncate a file to a specified length. * @param fd A file descriptor. */ export function ftruncate(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace ftruncate { /** * Asynchronous ftruncate(2) - Truncate a file to a specified length. @@ -359,21 +622,23 @@ declare module 'fs' { */ function __promisify__(fd: number, len?: number | null): Promise; } - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] */ export function ftruncateSync(fd: number, len?: number | null): 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. + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 */ export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace chown { /** * Asynchronous chown(2) - Change ownership of a file. @@ -381,20 +646,22 @@ declare module 'fs' { */ function __promisify__(path: PathLike, uid: number, gid: number): Promise; } - /** - * Synchronous 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. + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 */ export function chownSync(path: PathLike, uid: number, gid: number): void; - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 */ export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace fchown { /** * Asynchronous fchown(2) - Change ownership of a file. @@ -402,20 +669,22 @@ declare module 'fs' { */ function __promisify__(fd: number, uid: number, gid: number): Promise; } - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. */ export function fchownSync(fd: number, uid: number, gid: number): 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. + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. */ export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace lchown { /** * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. @@ -423,24 +692,24 @@ declare module 'fs' { */ function __promisify__(path: PathLike, uid: number, gid: number): Promise; } - /** - * Synchronous 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. + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. */ export function lchownSync(path: PathLike, uid: number, gid: number): void; - /** - * Changes the access and modification times of a file in the same way as `fs.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 {@link 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. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 */ - export function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; export namespace lutimes { /** * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, @@ -450,27 +719,32 @@ declare module 'fs' { * @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. */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; } - /** - * Change the file system timestamps of the symbolic link referenced by `path`. Returns `undefined`, - * or throws an exception when parameters are incorrect or the operation fails. - * This is the synchronous version of `fs.lutimes()`. - * @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 symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 */ - export function lutimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): 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. + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 */ export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace chmod { /** * Asynchronous chmod(2) - Change permissions of a file. @@ -479,22 +753,22 @@ declare module 'fs' { */ function __promisify__(path: PathLike, mode: Mode): Promise; } - /** - * Synchronous 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. + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 */ export function chmodSync(path: PathLike, mode: Mode): void; - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 */ export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace fchmod { /** * Asynchronous fchmod(2) - Change permissions of a file. @@ -503,22 +777,24 @@ declare module 'fs' { */ function __promisify__(fd: number, mode: Mode): Promise; } - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 */ export function fchmodSync(fd: number, mode: Mode): 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. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 */ export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + /** @deprecated */ export namespace lchmod { /** * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. @@ -527,106 +803,294 @@ declare module 'fs' { */ function __promisify__(path: PathLike, mode: Mode): Promise; } - /** - * Synchronous 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. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 */ export function lchmodSync(path: PathLike, mode: Mode): void; - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 */ export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function stat(path: PathLike, options: StatOptions & { bigint?: false | undefined } | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function stat(path: PathLike, options: StatOptions & { bigint: true }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace stat { /** * Asynchronous stat(2) - Get file status. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ - function __promisify__(path: PathLike, options?: StatOptions & { bigint?: false | undefined }): Promise; - function __promisify__(path: PathLike, options: StatOptions & { bigint: true }): Promise; + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; function __promisify__(path: PathLike, options?: StatOptions): Promise; } - + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + } + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + } + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + } + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + } + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + } + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } /** * Synchronous stat(2) - Get file status. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ - export function statSync(path: PathLike, options?: StatOptions & { bigint?: false | undefined }): Stats; - export function statSync(path: PathLike, options: StatOptions & { bigint: true }): BigIntStats; - export function statSync(path: PathLike, options?: StatOptions): Stats | BigIntStats; - + export const statSync: StatSyncFn; /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 */ export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function fstat(fd: number, options: StatOptions & { bigint?: false | undefined } | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function fstat(fd: number, options: StatOptions & { bigint: true }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace fstat { /** * Asynchronous fstat(2) - Get file status. * @param fd A file descriptor. */ - function __promisify__(fd: number, options?: StatOptions & { bigint?: false | undefined }): Promise; - function __promisify__(fd: number, options: StatOptions & { bigint: true }): Promise; + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + } + ): Promise; function __promisify__(fd: number, options?: StatOptions): Promise; } - /** * Synchronous fstat(2) - Get file status. * @param fd A file descriptor. */ - export function fstatSync(fd: number, options?: StatOptions & { bigint?: false | undefined }): Stats; - export function fstatSync(fd: number, options: StatOptions & { bigint: true }): BigIntStats; + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + } + ): BigIntStats; export function fstatSync(fd: number, options?: StatOptions): 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. + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 */ export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function lstat(path: PathLike, options: StatOptions & { bigint?: false | undefined } | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function lstat(path: PathLike, options: StatOptions & { bigint: true }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace lstat { /** * 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. */ - function __promisify__(path: PathLike, options?: StatOptions & { bigint?: false | undefined }): Promise; - function __promisify__(path: PathLike, options: StatOptions & { bigint: true }): Promise; + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; function __promisify__(path: PathLike, options?: StatOptions): Promise; } - /** * Synchronous 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. */ - export function lstatSync(path: PathLike, options?: StatOptions & { bigint?: false | undefined }): Stats; - export function lstatSync(path: PathLike, options: StatOptions & { bigint: true }): BigIntStats; - export function lstatSync(path: PathLike, options?: StatOptions): Stats | BigIntStats; - + export const lstatSync: StatSyncFn; /** - * 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. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 */ export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace link { /** * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. @@ -635,31 +1099,49 @@ declare module 'fs' { */ function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; } - /** - * Synchronous 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. Returns `undefined`. + * @since v0.1.31 */ export function linkSync(existingPath: PathLike, newPath: PathLike): void; - /** - * 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 the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, 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. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './example/mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` in the `example` which points + * to `mew` in the same directory: + * + * ```bash + * $ tree example/ + * example/ + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 */ export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; - /** * 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. */ export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace symlink { /** * Asynchronous symlink(2) - Create a new symbolic link to an existing file. @@ -669,193 +1151,220 @@ declare module 'fs' { * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. */ function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - type Type = "dir" | "file" | "junction"; + type Type = 'dir' | 'file' | 'junction'; } - /** - * Synchronous 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. + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 */ export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - /** - * 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`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * 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 passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 */ - export function readlink( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void - ): void; - + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; /** * 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. */ export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - /** * 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. */ - export function readlink(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; - + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; /** * 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. */ export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace readlink { /** * 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. */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function __promisify__(path: PathLike, options?: EncodingOption): Promise; /** * 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. */ function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - /** * 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. */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; + function __promisify__(path: PathLike, options?: EncodingOption): Promise; } - /** - * Synchronous 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. + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * 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 v0.1.31 */ - export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - + export function readlinkSync(path: PathLike, options?: EncodingOption): string; /** * Synchronous 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. */ export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; - /** * Synchronous 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. */ - export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; /** - * 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. + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * 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 passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 */ - export function realpath( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; /** * 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. */ export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - /** * 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. */ - export function realpath(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; /** * 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. */ export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace realpath { /** * 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 __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function __promisify__(path: PathLike, options?: EncodingOption): Promise; /** * 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 __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - /** * 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 __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - - function native( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * 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 passed to the callback. 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 v9.2.0 + */ + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - function native(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; } - /** - * Synchronous 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. + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 */ - export function realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - + export function realpathSync(path: PathLike, options?: EncodingOption): string; /** * Synchronous 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. */ export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; - /** * Synchronous 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. */ - export function realpathSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; export namespace realpathSync { - function native(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + function native(path: PathLike, options?: EncodingOption): string; function native(path: PathLike, options: BufferEncodingOption): Buffer; - function native(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; } - /** - * 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. + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 */ export function unlink(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace unlink { /** * Asynchronous unlink(2) - delete a name and possibly the file it refers to. @@ -863,13 +1372,11 @@ declare module 'fs' { */ function __promisify__(path: PathLike): Promise; } - /** - * Synchronous 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. + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 */ export function unlinkSync(path: PathLike): void; - export interface RmDirOptions { /** * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or @@ -881,14 +1388,12 @@ declare module 'fs' { */ maxRetries?: number | undefined; /** - * @deprecated since v14.14.0 In future versions of Node.js, - * `fs.rmdir(path, { recursive: true })` will throw on nonexistent - * paths, or when given a file as a target. + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. * Use `fs.rm(path, { recursive: true, force: true })` instead. * * If `true`, perform a recursive directory removal. In - * recursive mode, errors are not reported if `path` does not exist, and - * operations are retried on failure. + * recursive mode soperations are retried on failure. * @default false */ recursive?: boolean | undefined; @@ -899,15 +1404,18 @@ declare module 'fs' { */ retryDelay?: number | undefined; } - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 */ export function rmdir(path: PathLike, callback: NoParamCallback): void; export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace rmdir { /** * Asynchronous rmdir(2) - delete a directory. @@ -915,13 +1423,16 @@ declare module 'fs' { */ function __promisify__(path: PathLike, options?: RmDirOptions): Promise; } - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 */ export function rmdirSync(path: PathLike, options?: RmDirOptions): void; - export interface RmOptions { /** * When `true`, exceptions will be ignored if `path` does not exist. @@ -939,8 +1450,7 @@ declare module 'fs' { maxRetries?: number | undefined; /** * If `true`, perform a recursive directory removal. In - * recursive mode, errors are not reported if `path` does not exist, and - * operations are retried on failure. + * recursive mode, operations are retried on failure. * @default false */ recursive?: boolean | undefined; @@ -951,26 +1461,24 @@ declare module 'fs' { */ retryDelay?: number | undefined; } - /** - * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 */ export function rm(path: PathLike, callback: NoParamCallback): void; export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace rm { /** * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). */ function __promisify__(path: PathLike, options?: RmOptions): Promise; } - /** - * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 */ export function rmSync(path: PathLike, options?: RmOptions): void; - export interface MakeDirectoryOptions { /** * Indicates whether parent folders should be created. @@ -984,23 +1492,65 @@ declare module 'fs' { */ mode?: Mode | undefined; } - + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * 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`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void + ): 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`. */ - export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): 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`. - */ - export function mkdir(path: PathLike, options: Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null | undefined, callback: NoParamCallback): void; - + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback + ): 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. @@ -1008,14 +1558,11 @@ declare module 'fs' { * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; - /** * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function mkdir(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace mkdir { /** * Asynchronous mkdir(2) - create a directory. @@ -1023,16 +1570,27 @@ declare module 'fs' { * @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 __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; - + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; /** * 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 __promisify__(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null): Promise; - + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1041,23 +1599,34 @@ declare module 'fs' { */ function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; } - + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): string | undefined; /** * Synchronous 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`. */ - export function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string | undefined; - - /** - * Synchronous 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`. - */ - export function mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null): void; - + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): void; /** * Synchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1065,90 +1634,157 @@ declare module 'fs' { * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; - + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. 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 created directory path is passed as a string to the callback's second + * parameter. + * + * 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 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; /** * 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. */ - export function mkdtemp(prefix: string, options: BaseEncodingOptions | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - + export function mkdtemp( + prefix: string, + options: + | 'buffer' + | { + encoding: 'buffer'; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + ): void; /** * 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. */ - export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; - - /** - * 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. - */ - export function mkdtemp(prefix: string, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; - + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; /** * Asynchronously creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. */ export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace mkdtemp { /** * 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. */ - function __promisify__(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function __promisify__(prefix: string, options?: EncodingOption): Promise; /** * 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. */ function __promisify__(prefix: string, options: BufferEncodingOption): Promise; - /** * 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. */ - function __promisify__(prefix: string, options?: BaseEncodingOptions | string | null): Promise; + function __promisify__(prefix: string, options?: EncodingOption): Promise; } - /** - * Synchronously 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. + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 */ - export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): string; - + export function mkdtempSync(prefix: string, options?: EncodingOption): string; /** * Synchronously 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. */ export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; - /** * Synchronously 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. */ - export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | string | null): string | Buffer; - + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; /** - * 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 callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * 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 passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 */ export function readdir( path: PathLike, - options: { encoding: BufferEncoding | null; withFileTypes?: false | undefined } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void ): void; - /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1156,10 +1792,14 @@ declare module 'fs' { */ export function readdir( path: PathLike, - options: { encoding: "buffer"; withFileTypes?: false | undefined } | "buffer", + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer', callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void ): void; - /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1167,89 +1807,161 @@ declare module 'fs' { */ export function readdir( path: PathLike, - options: BaseEncodingOptions & { withFileTypes?: false | undefined } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void ): void; - /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - /** * Asynchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. */ - export function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + ): void; export namespace readdir { /** * 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. */ - function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false | undefined } | BufferEncoding | null): Promise; - + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): Promise; /** * 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. */ - function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false | undefined }): Promise; - + function __promisify__( + path: PathLike, + options: + | 'buffer' + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + ): Promise; /** * 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. */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false | undefined } | BufferEncoding | null): Promise; - + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; /** * 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 If called with `withFileTypes: true` the result data will be an array of Dirent */ - function __promisify__(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; } - + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * 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 returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): string[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false | undefined } | BufferEncoding | null): string[]; - + export function readdirSync( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Buffer[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false | undefined } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false | undefined } | BufferEncoding | null): string[] | Buffer[]; - + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): string[] | Buffer[]; /** * Synchronous readdir(3) - read a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. */ - export function readdirSync(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Dirent[]; - + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Dirent[]; /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 */ - export function close(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function close(fd: number, callback?: NoParamCallback): void; export namespace close { /** * Asynchronous close(2) - close a file descriptor. @@ -1257,27 +1969,45 @@ declare module 'fs' { */ function __promisify__(fd: number): Promise; } - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 */ export function closeSync(fd: number): 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`. + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * 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). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] */ - export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - + export function open(path: PathLike, flags: OpenMode | undefined, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param [flags='r'] See `support of file system `flags``. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: OpenMode | undefined, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; /** * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ - export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; export namespace open { /** * Asynchronous open(2) - open and possibly create a file. @@ -1286,23 +2016,26 @@ declare module 'fs' { */ function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; } - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @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`. + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] */ export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; - /** - * 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 in seconds,`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 v0.4.2 */ - export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; export namespace utimes { /** * Asynchronously change file timestamps of the file referenced by the supplied path. @@ -1310,26 +2043,22 @@ declare module 'fs' { * @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. */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; } - /** - * Synchronously 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. + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 */ - export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @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 supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 */ - export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; export namespace futimes { /** * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. @@ -1337,24 +2066,21 @@ declare module 'fs' { * @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. */ - function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; } - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @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. + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 */ - export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. + * 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. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 */ export function fsync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace fsync { /** * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. @@ -1362,19 +2088,37 @@ declare module 'fs' { */ function __promisify__(fd: number): Promise; } - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. + * 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. Returns `undefined`. + * @since v0.1.96 */ export function fsyncSync(fd: number): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @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. + * Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it + * must have an own `toString` function property. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * 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 v0.0.2 */ export function write( fd: number, @@ -1382,9 +2126,8 @@ declare module 'fs' { offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void ): void; - /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. @@ -1396,9 +2139,8 @@ declare module 'fs' { buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void ): void; - /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. @@ -1410,13 +2152,11 @@ declare module 'fs' { offset: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void ): void; - /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. */ export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; - /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. @@ -1429,9 +2169,8 @@ declare module 'fs' { string: string, position: number | undefined | null, encoding: BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void ): void; - /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. @@ -1439,15 +2178,12 @@ declare module 'fs' { * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. * @param string A string to write. */ export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace write { /** * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. @@ -1461,9 +2197,11 @@ declare module 'fs' { buffer?: TBuffer, offset?: number, length?: number, - position?: number | null, - ): Promise<{ bytesWritten: number, buffer: TBuffer }>; - + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; /** * Asynchronously writes `string` to the file referenced by the supplied file descriptor. * @param fd A file descriptor. @@ -1471,18 +2209,25 @@ declare module 'fs' { * @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 __promisify__(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; } - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @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. + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. */ export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; - /** * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. * @param fd A file descriptor. @@ -1491,25 +2236,32 @@ declare module 'fs' { * @param encoding The expected string encoding. */ export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; - + export type ReadPosition = number | bigint; /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. + * @param offset The position in `buffer` to write the data to. * @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 Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. */ export function read( fd: number, buffer: TBuffer, offset: number, length: number, - position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace read { /** * @param fd A file descriptor. @@ -1524,9 +2276,11 @@ declare module 'fs' { offset: number, length: number, position: number | null - ): Promise<{ bytesRead: number, buffer: TBuffer }>; + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; } - export interface ReadSyncOptions { /** * @default 0 @@ -1539,74 +2293,139 @@ declare module 'fs' { /** * @default null */ - position?: number | null | undefined; + position?: ReadPosition | null | undefined; } - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @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. + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 */ - export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; - + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; /** * Similar to the above `fs.readSync` function, this version takes an optional `options` object. * If no `options` object is specified, it will default with the above values. */ export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; - /** * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor */ export function readFile( - path: PathLike | number, - options: { encoding?: null | undefined; flag?: string | undefined; } | undefined | null, + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void ): void; - /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ export function readFile( - path: PathLike | number, - options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding, + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, callback: (err: NodeJS.ErrnoException | null, data: string) => void ): void; - /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ export function readFile( - path: PathLike | number, - options: BaseEncodingOptions & { flag?: string | undefined; } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void ): void; - /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. */ - export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; export namespace readFile { /** * Asynchronously reads the entire contents of a file. @@ -1615,8 +2434,13 @@ declare module 'fs' { * @param options An object that may contain an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - function __promisify__(path: PathLike | number, options?: { encoding?: null | undefined; flag?: string | undefined; } | null): Promise; - + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Promise; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1625,8 +2449,15 @@ declare module 'fs' { * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - function __promisify__(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding): Promise; - + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): Promise; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -1635,64 +2466,158 @@ declare module 'fs' { * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - function __promisify__(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string | undefined; } | BufferEncoding | null): Promise; + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): Promise; } - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor 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'`. + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor */ - export function readFileSync(path: PathLike | number, options?: { encoding?: null | undefined; flag?: string | undefined; } | null): Buffer; - + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Buffer; /** * Synchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - export function readFileSync(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding): string; - + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): string; /** * Synchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. * If a file descriptor is provided, the underlying file will _not_ be closed automatically. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - export function readFileSync(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string | undefined; } | BufferEncoding | null): string | Buffer; - - export type WriteFileOptions = BaseEncodingOptions & { mode?: Mode | undefined; flag?: string | undefined; } | BufferEncoding | null; - + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): string | Buffer; + export type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; /** * Asynchronously writes data to a file, replacing the file if it already exists. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor 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. - */ - export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. * If a file descriptor 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. */ - export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; export namespace writeFile { /** * Asynchronously writes data to a file, replacing the file if it already exists. @@ -1706,47 +2631,82 @@ declare module 'fs' { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'w'` is used. */ - function __promisify__(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; } - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor 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. + * Returns `undefined`. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor */ - export function writeFileSync(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; - + export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): 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 file descriptor 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. - */ - export function appendFile(file: PathLike | number, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): 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 file descriptor 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. */ - export function appendFile(file: PathLike | number, data: string | Uint8Array, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; export namespace appendFile { /** * Asynchronously append data to a file, creating the file if it does not exist. @@ -1760,103 +2720,333 @@ declare module 'fs' { * If `mode` is a string, it is parsed as an octal integer. * If `flag` is not supplied, the default of `'a'` is used. */ - function __promisify__(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): Promise; + function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise; } - /** - * Synchronously 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 file descriptor 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. + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor */ - export function appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void; - + export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 */ - export function watchFile(filename: PathLike, options: { persistent?: boolean | undefined; interval?: number | undefined; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: (curr: BigIntStats, prev: BigIntStats) => void + ): StatWatcher; /** * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. */ - export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): StatWatcher; /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` */ export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | 'buffer' | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = 'rename' | 'change'; + export type WatchListener = (event: WatchEventType, filename: T) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer', + listener?: WatchListener + ): FSWatcher; /** * 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. - * URL support is _experimental_. * @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. */ - export function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null | undefined, persistent?: boolean | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, - listener?: (event: "rename" | "change", filename: string) => void, - ): FSWatcher; - + export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener): FSWatcher; /** * 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. - * URL support is _experimental_. * @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. */ - export function watch( - filename: PathLike, - options: { encoding: "buffer", persistent?: boolean | undefined, recursive?: boolean | undefined; } | "buffer", - listener?: (event: "rename" | "change", filename: Buffer) => void - ): FSWatcher; - + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; /** * 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. - * URL support is _experimental_. - * @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. */ - export function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null | undefined, persistent?: boolean | undefined, recursive?: boolean | undefined } | string | null, - listener?: (event: "rename" | "change", filename: string | Buffer) => void, - ): FSWatcher; - + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; /** - * 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. - * URL support is _experimental_. - */ - export function watch(filename: PathLike, listener?: (event: "rename" | "change", filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated since v1.0.0 Use `fs.stat()` or `fs.access()` instead - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` 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 does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. */ export function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + /** @deprecated */ export namespace exists { /** * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. @@ -1864,79 +3054,70 @@ declare module 'fs' { */ function __promisify__(path: PathLike): Promise; } - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 */ export function existsSync(path: PathLike): boolean; - export namespace constants { // File Access Constants - /** Constant for fs.access(). File is visible to the calling process. */ const F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ const R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ const W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ const X_OK: number; - // File Copy Constants - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ const COPYFILE_EXCL: number; - /** * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. */ const COPYFILE_FICLONE: number; - /** * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. * If the underlying platform does not support copy-on-write, then the operation will fail with an error. */ const COPYFILE_FICLONE_FORCE: number; - // File Open Constants - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ const O_RDONLY: number; - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ const O_WRONLY: number; - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ const O_RDWR: number; - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ const O_CREAT: number; - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ const O_EXCL: number; - /** * Constant for fs.open(). Flag indicating that if path identifies a terminal device, * opening the path shall not cause that terminal to become the controlling terminal for the process * (if the process does not already have one). */ const O_NOCTTY: number; - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ const O_TRUNC: number; - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ const O_APPEND: number; - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ const O_DIRECTORY: number; - /** * constant for fs.open(). * Flag indicating reading accesses to the file system will no longer result in @@ -1944,89 +3125,60 @@ declare module 'fs' { * This flag is available on Linux operating systems only. */ const O_NOATIME: number; - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ const O_NOFOLLOW: number; - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ const O_SYNC: number; - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ const O_DSYNC: number; - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ const O_SYMLINK: number; - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ const O_DIRECT: number; - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ const O_NONBLOCK: number; - // File Type Constants - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ const S_IFMT: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ const S_IFREG: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ const S_IFDIR: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ const S_IFCHR: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ const S_IFBLK: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ const S_IFIFO: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ const S_IFLNK: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ const S_IFSOCK: number; - // File Mode Constants - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ const S_IRWXU: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ const S_IRUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ const S_IWUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ const S_IXUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ const S_IRWXG: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ const S_IRGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ const S_IWGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ const S_IXGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ const S_IRWXO: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ const S_IROTH: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ const S_IWOTH: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ const S_IXOTH: number; - /** * When set, a memory file mapping is used to access the file. This flag * is available on Windows operating systems only. On other operating systems, @@ -2034,22 +3186,177 @@ declare module 'fs' { */ const UV_FS_O_FILEMAP: number; } - /** - * 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. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file exists in the current directory, and if it is writable. + * access(file, constants.F_OK | constants.W_OK, (err) => { + * if (err) { + * console.error( + * `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); + * } else { + * console.log(`${file} exists, and it is writable`); + * } + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. 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. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] */ export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; - /** * 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_. */ export function access(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace access { /** * Asynchronously tests a user's permissions for the file specified by path. @@ -2058,23 +3365,35 @@ declare module 'fs' { */ function __promisify__(path: PathLike, mode?: number): Promise; } - /** - * Synchronously 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_. + * Synchronously 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. Check `File access constants` for + * possible values of `mode`. It is possible to create a mask consisting of + * the bitwise OR of two or more values + * (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] */ export function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createReadStream(path: PathLike, options?: BufferEncoding | { + interface StreamOptions { flags?: string | undefined; encoding?: BufferEncoding | undefined; - fd?: number | undefined; + fd?: number | promises.FileHandle | undefined; mode?: number | undefined; autoClose?: boolean | undefined; /** @@ -2082,33 +3401,112 @@ declare module 'fs' { */ emitClose?: boolean | undefined; start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { end?: number | undefined; - highWaterMark?: number | undefined; - }): ReadStream; - + } /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` 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. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * 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. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 */ - export function createWriteStream(path: PathLike, options?: BufferEncoding | { - flags?: string | undefined; - encoding?: BufferEncoding | undefined; - fd?: number | undefined; - mode?: number | undefined; - autoClose?: boolean | undefined; - emitClose?: boolean | undefined; - start?: number | undefined; - highWaterMark?: number | undefined; - }): WriteStream; - + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. + * `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` option to be set to `r+` rather than the default `w`. + * 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. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions): 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. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 */ export function fdatasync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace fdatasync { /** * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. @@ -2116,123 +3514,166 @@ declare module 'fs' { */ function __promisify__(fd: number): Promise; } - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. + * 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. Returns `undefined`. + * @since v0.1.96 */ export function fdatasyncSync(fd: number): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * 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. + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. 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. + * + * `mode` is an optional integer that specifies 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`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. */ export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * 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 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. - */ - export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; export namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * 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. - */ - function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; } - /** - * Synchronously 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. + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. 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. + * + * `mode` is an optional integer that specifies 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`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. */ - export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; - + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; /** - * Write an array of ArrayBufferViews to the file specified by fd using writev(). - * position is the offset from the beginning of the file where this data should be written. - * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * * 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. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 */ - export function writev( - fd: number, - buffers: ReadonlyArray, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function writev( fd: number, buffers: ReadonlyArray, position: number, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void ): void; - export interface WriteVResult { bytesWritten: number; buffers: NodeJS.ArrayBufferView[]; } - export namespace writev { function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; } - /** - * See `writev`. + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. */ export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; - - export function readv( - fd: number, - buffers: ReadonlyArray, - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; export function readv( fd: number, buffers: ReadonlyArray, position: number, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void ): void; - export interface ReadVResult { bytesRead: number; buffers: NodeJS.ArrayBufferView[]; } - export namespace readv { function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; } - /** - * See `readv`. + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. */ export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; - export interface OpenDirOptions { encoding?: BufferEncoding | undefined; /** @@ -2243,33 +3684,118 @@ declare module 'fs' { */ bufferSize?: number | undefined; } - + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * 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. + * @since v12.12.0 + */ export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; - + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * 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. + * @since v12.12.0 + */ export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; export function opendir(path: PathLike, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - export namespace opendir { function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; } - export interface BigIntStats extends StatsBase { - } - - export class BigIntStats { atimeNs: bigint; mtimeNs: bigint; ctimeNs: bigint; birthtimeNs: bigint; } - export interface BigIntOptions { bigint: true; } - export interface StatOptions { bigint?: boolean | undefined; } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * 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. + */ + export function cp(source: string | URL, destination: string | URL, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function cp(source: string | URL, destination: string | URL, opts: CopyOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** + * Synchronously 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. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; } declare module 'node:fs' { export * from 'fs'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/fs/promises.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/fs/promises.d.ts index 9a17ec577..ca6dde66c 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/fs/promises.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/fs/promises.d.ts @@ -1,303 +1,560 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * 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 { - Stats, BigIntStats, - StatOptions, - WriteVResult, - ReadVResult, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, PathLike, + ReadStream, + ReadVResult, RmDirOptions, RmOptions, - MakeDirectoryOptions, - Dirent, - OpenDirOptions, - Dir, - BaseEncodingOptions, - BufferEncodingOption, - OpenMode, - Mode, - } from 'fs'; - + StatOptions, + Stats, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from 'node:fs'; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @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; + } + // 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 | undefined, flag?: OpenMode | undefined } | BufferEncoding | null): Promise; - + appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; /** - * 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; - /** - * 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; - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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; - /** - * 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 Fufills with `undefined` upon success. */ sync(): Promise; - /** - * 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(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - + read(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * 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; /** * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. * The `FileHandle` must have been opened for reading. * @param options An object that may contain an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - readFile(options?: { encoding?: null | undefined, flag?: OpenMode | undefined } | null): Promise; - + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding + ): Promise; /** * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. * The `FileHandle` must have been opened for reading. * @param options An object that may contain an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - readFile(options: { encoding: BufferEncoding, flag?: OpenMode | undefined } | BufferEncoding): Promise; - + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. */ - readFile(options?: BaseEncodingOptions & { flag?: OpenMode | undefined } | BufferEncoding | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - */ - stat(opts?: StatOptions & { bigint?: false | undefined }): Promise; - stat(opts: StatOptions & { bigint: true }): Promise; + stat( + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + } + ): Promise; stat(opts?: StatOptions): Promise; - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param len If not specified, defaults to `0`. + * 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 '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; - /** - * 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; - /** - * 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 + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object, or an + * object with an own `toString` function + * property. 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(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; /** - * 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. + * + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * 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 `fs.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=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength] The number of bytes from `buffer` to write. + * @param position 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( + 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. - */ - writeFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode | undefined, flag?: OpenMode | undefined } | BufferEncoding | null): Promise; - - /** - * See `fs.writev` promisified version. + * 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 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. */ writev(buffers: ReadonlyArray, position?: number): Promise; - /** - * See `fs.readv` 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 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: */ readv(buffers: ReadonlyArray, position?: number): Promise; - /** - * Asynchronous close(2) - close a `FileHandle`. + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from '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. */ close(): Promise; } + 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. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * 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 } from 'fs/promises'; + * import { constants } from 'fs'; + * + * 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; - /** - * 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 { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('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.log('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; - + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; /** - * 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; - + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; /** - * 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. - */ - function read( - 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( - 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_. + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. */ function rename(oldPath: PathLike, newPath: PathLike): Promise; - /** - * 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; - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param handle A `FileHandle`. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(handle: FileHandle, len?: number): Promise; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * 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 rmdir(path: PathLike, options?: RmDirOptions): Promise; - /** - * 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; - /** - * 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. + * @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; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param handle A `FileHandle`. - */ - function fsync(handle: FileHandle): Promise; - + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; /** * 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: MakeDirectoryOptions & { recursive: true; }): Promise; - - /** - * 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 & { recursive?: false | undefined; }) | null): Promise; - + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -305,238 +562,404 @@ declare module 'fs/promises' { * 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; - + /** + * 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 '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?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; /** * 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. */ - function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false | undefined } | BufferEncoding | null): Promise; - + function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Promise; /** * 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. */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false | undefined } | "buffer"): Promise; - - /** - * 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. - */ - function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false | undefined } | BufferEncoding | null): Promise; - + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; /** * 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 If called with `withFileTypes: true` the result data will be an array of Dirent. */ - function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; - + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; /** - * 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; - + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** * 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. */ function readlink(path: PathLike, options: BufferEncodingOption): Promise; - /** * 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. */ - function readlink(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; /** - * 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'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. */ function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; - /** - * 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. + * 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 lstat(path: PathLike, opts?: StatOptions & { bigint?: false | undefined }): Promise; - function lstat(path: PathLike, opts: StatOptions & { bigint: true }): Promise; + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; function lstat(path: PathLike, opts?: StatOptions): Promise; - /** - * 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 v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. */ - function stat(path: PathLike, opts?: StatOptions & { bigint?: false | undefined }): Promise; - function stat(path: PathLike, opts: StatOptions & { bigint: true }): Promise; + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; function stat(path: PathLike, opts?: StatOptions): Promise; - /** - * 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; - /** - * 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; - /** - * 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. - */ - function fchmod(handle: FileHandle, mode: Mode): Promise; - - /** - * 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. + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. */ function chmod(path: PathLike, mode: Mode): Promise; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param handle A `FileHandle`. - */ - function fchown(handle: FileHandle, uid: number, gid: number): Promise; - - /** - * 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. + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. */ function chown(path: PathLike, uid: number, gid: number): Promise; - /** - * 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; - /** - * 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; - - /** - * 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?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** * 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; - /** * 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?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** - * 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 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.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('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. */ - function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** * 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. */ function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; - /** * 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. */ - function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** - * 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`, or, an object with an own (not inherited)`toString` function property. + * + * 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()`. + * + * 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 'fs/promises'; + * import { Buffer } from '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 | undefined, flag?: OpenMode | undefined } | BufferEncoding | null + file: PathLike | FileHandle, + data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null ): Promise; - /** - * 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( + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * 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. + * + * 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 '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, - data: string | Uint8Array, - options?: BaseEncodingOptions & { mode?: Mode | undefined, flag?: OpenMode | undefined } | BufferEncoding | null - ): Promise; - + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null + ): Promise; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -544,8 +967,15 @@ declare module 'fs/promises' { * @param options An object that may contain an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: null | undefined, flag?: OpenMode | undefined } | null): Promise; - + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + ): Promise; /** * Asynchronously reads the entire contents of a file. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. @@ -553,18 +983,114 @@ declare module 'fs/promises' { * @param options An object that may contain an optional flag. * If a flag is not provided, it defaults to `'r'`. */ - function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: OpenMode | undefined } | BufferEncoding): Promise; - + function readFile( + path: PathLike | FileHandle, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. + * 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 '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 readFile(path: PathLike | FileHandle, options?: BaseEncodingOptions & { flag?: OpenMode | undefined } | BufferEncoding | null): Promise; - function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('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 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer' + ): AsyncIterable>; + /** + * 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>; + /** + * 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> | AsyncIterable>; + /** + * 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; } declare module 'node:fs/promises' { export * from 'fs/promises'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/globals.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/globals.d.ts index e47f1b300..ca9edd437 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/globals.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/globals.d.ts @@ -16,23 +16,6 @@ interface ErrorConstructor { 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; -} - /*-----------------------------------------------* * * * GLOBAL * @@ -40,9 +23,9 @@ interface ImportMeta { ------------------------------------------------*/ // For backwards compability -interface NodeRequire extends NodeJS.Require {} -interface RequireResolve extends NodeJS.RequireResolve {} -interface NodeModule extends NodeJS.Module {} +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } declare var process: NodeJS.Process; declare var console: Console; @@ -50,61 +33,36 @@ declare var console: Console; declare var __filename: string; declare var __dirname: string; -declare function setTimeout(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -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; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -declare function queueMicrotask(callback: () => void): void; - declare var require: NodeRequire; declare var module: NodeModule; // Same as module.exports declare var exports: any; -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"; - -type WithImplicitCoercion = T | { valueOf(): T }; +/** + * Only available if `--expose-gc` is passed to the process. + */ +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. - * @since v14.7.0 - */ +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ interface AbortController { /** * Returns the AbortSignal object associated with this object. - * @since v14.7.0 */ + readonly signal: AbortSignal; /** * 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. - * @since v14.7.0 */ abort(): 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. - * @since v14.7.0 - */ +/** 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 { /** * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. - * @since v14.7.0 */ readonly aborted: boolean; } @@ -117,335 +75,35 @@ declare var AbortController: { declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; - // TODO: Add abort() static + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; }; //#endregion borrowed -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' - */ -declare class Buffer extends Uint8Array { +//#region ArrayLike.at() +interface RelativeIndexable { /** - * 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. + * 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. */ - constructor(str: string, encoding?: BufferEncoding); - /** - * 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()`). - */ - constructor(size: number); - /** - * 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. - */ - constructor(array: Uint8Array); - /** - * 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. - */ - constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); - /** - * 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. - */ - constructor(array: ReadonlyArray); - /** - * 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, 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): Buffer; - static from(data: WithImplicitCoercion | 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 | { [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'|'base64url'|'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, 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; - - 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; - /** - * 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`. - */ - 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; - /** - * @alias Buffer.writeBigUInt64BE - * @since v14.10.0, v12.19.0 - */ - writeBigUint64BE(value: bigint, offset?: number): number; - writeBigUInt64LE(value: bigint, offset?: number): number; - /** - * @alias Buffer.writeBigUInt64LE - * @since v14.10.0, v12.19.0 - */ - writeBigUint64LE(value: bigint, offset?: number): number; - writeUIntLE(value: number, offset: number, byteLength: number): number; - /** - * @alias Buffer.writeUIntLE - * @since v14.9.0, v12.19.0 - */ - writeUintLE(value: number, offset: number, byteLength: number): number; - writeUIntBE(value: number, offset: number, byteLength: number): number; - /** - * @alias Buffer.writeUIntBE - * @since v14.9.0, v12.19.0 - */ - 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; - /** - * @alias Buffer.readBigUInt64BE - * @since v14.10.0, v12.19.0 - */ - readBigUint64BE(offset?: number): bigint; - readBigUInt64LE(offset?: number): bigint; - /** - * @alias Buffer.readBigUInt64LE - * @since v14.10.0, v12.19.0 - */ - readBigUint64LE(offset?: number): bigint; - readBigInt64BE(offset?: number): bigint; - readBigInt64LE(offset?: number): bigint; - readUIntLE(offset: number, byteLength: number): number; - /** - * @alias Buffer.readUIntLE - * @since v14.9.0, v12.19.0 - */ - readUintLE(offset: number, byteLength: number): number; - readUIntBE(offset: number, byteLength: number): number; - /** - * @alias Buffer.readUIntBE - * @since v14.9.0, v12.19.0 - */ - readUintBE(offset: number, byteLength: number): number; - readIntLE(offset: number, byteLength: number): number; - readIntBE(offset: number, byteLength: number): number; - readUInt8(offset?: number): number; - /** - * @alias Buffer.readUInt8 - * @since v14.9.0, v12.19.0 - */ - readUint8(offset?: number): number; - readUInt16LE(offset?: number): number; - /** - * @alias Buffer.readUInt16LE - * @since v14.9.0, v12.19.0 - */ - readUint16LE(offset?: number): number; - readUInt16BE(offset?: number): number; - /** - * @alias Buffer.readUInt16BE - * @since v14.9.0, v12.19.0 - */ - readUint16BE(offset?: number): number; - readUInt32LE(offset?: number): number; - /** - * @alias Buffer.readUInt32LE - * @since v14.9.0, v12.19.0 - */ - readUint32LE(offset?: number): number; - readUInt32BE(offset?: number): number; - /** - * @alias Buffer.readUInt32BE - * @since v14.9.0, v12.19.0 - */ - 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; - /** - * @alias Buffer.writeUInt8 - * @since v14.9.0, v12.19.0 - */ - writeUint8(value: number, offset?: number): number; - writeUInt16LE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt16LE - * @since v14.9.0, v12.19.0 - */ - writeUint16LE(value: number, offset?: number): number; - writeUInt16BE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt16BE - * @since v14.9.0, v12.19.0 - */ - writeUint16BE(value: number, offset?: number): number; - writeUInt32LE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt32LE - * @since v14.9.0, v12.19.0 - */ - writeUint32LE(value: number, offset?: number): number; - writeUInt32BE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt32BE - * @since v14.9.0, v12.19.0 - */ - 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; - - fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; - - 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; - values(): IterableIterator; + at(index: number): T | undefined; } +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface ReadonlyArray extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} +//#endregion ArrayLike.at() end /*----------------------------------------------* * * @@ -453,52 +111,11 @@ declare class Buffer extends Uint8Array { * * *-----------------------------------------------*/ 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 | undefined; - showHidden?: boolean | undefined; - /** - * @default 2 - */ - depth?: number | null | undefined; - colors?: boolean | undefined; - customInspect?: boolean | undefined; - showProxy?: boolean | undefined; - maxArrayLength?: number | null | undefined; - /** - * 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 | undefined; - breakLength?: number | undefined; - /** - * 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 | undefined; - sorted?: boolean | ((a: string, b: string) => number) | undefined; - } - interface CallSite { /** * Value of "this" */ - getThis(): any; + getThis(): unknown; /** * Type of "this" as a string. @@ -593,99 +210,18 @@ declare namespace NodeJS { writable: boolean; write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): this; - end(data: string | Uint8Array, cb?: () => void): this; - end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: BufferEncoding, cb?: () => void): void; } 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 { ref(): this; unref(): 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 = | Uint8Array | Uint8ClampedArray @@ -722,16 +258,20 @@ declare namespace NodeJS { '.node': (m: Module, filename: string) => any; } interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; exports: any; require: Require; id: string; filename: string; loaded: boolean; - /** @deprecated since 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 * * The directory name of the module. This is usually the same as the path.dirname() of the module.id. */ diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/http.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/http.d.ts index 9592ff1ff..ed5857081 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/http.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/http.d.ts @@ -1,14 +1,54 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'mysite.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'mysite.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/http.js) + */ declare module 'http' { - import * as stream from 'stream'; - import { URL } from 'url'; - import { Socket, Server as NetServer, LookupFunction } from 'net'; - + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { TcpSocketConnectOpts, Socket, Server as NetServer, LookupFunction } from 'node:net'; // incoming headers will never contain number interface IncomingHttpHeaders extends NodeJS.Dict { - 'accept'?: string | undefined; + accept?: string | undefined; 'accept-language'?: string | undefined; 'accept-patch'?: string | undefined; 'accept-ranges'?: string | undefined; @@ -20,12 +60,12 @@ declare module 'http' { 'access-control-max-age'?: string | undefined; 'access-control-request-headers'?: string | undefined; 'access-control-request-method'?: string | undefined; - 'age'?: string | undefined; - 'allow'?: string | undefined; + age?: string | undefined; + allow?: string | undefined; 'alt-svc'?: string | undefined; - 'authorization'?: string | undefined; + authorization?: string | undefined; 'cache-control'?: string | undefined; - 'connection'?: string | undefined; + connection?: string | undefined; 'content-disposition'?: string | undefined; 'content-encoding'?: string | undefined; 'content-language'?: string | undefined; @@ -33,27 +73,27 @@ declare module 'http' { 'content-location'?: string | undefined; 'content-range'?: string | undefined; 'content-type'?: string | undefined; - 'cookie'?: string | undefined; - 'date'?: string | undefined; - 'etag'?: string | undefined; - 'expect'?: string | undefined; - 'expires'?: string | undefined; - 'forwarded'?: string | undefined; - 'from'?: string | undefined; - 'host'?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; 'if-match'?: string | undefined; 'if-modified-since'?: string | undefined; 'if-none-match'?: string | undefined; 'if-unmodified-since'?: string | undefined; 'last-modified'?: string | undefined; - 'location'?: string | undefined; - 'origin'?: string | undefined; - 'pragma'?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; 'proxy-authenticate'?: string | undefined; 'proxy-authorization'?: string | undefined; 'public-key-pins'?: string | undefined; - 'range'?: string | undefined; - 'referer'?: string | undefined; + range?: string | undefined; + referer?: string | undefined; 'retry-after'?: string | undefined; 'sec-websocket-accept'?: string | undefined; 'sec-websocket-extensions'?: string | undefined; @@ -62,24 +102,21 @@ declare module 'http' { 'sec-websocket-version'?: string | undefined; 'set-cookie'?: string[] | undefined; 'strict-transport-security'?: string | undefined; - 'tk'?: string | undefined; - 'trailer'?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; 'transfer-encoding'?: string | undefined; - 'upgrade'?: string | undefined; + upgrade?: string | undefined; 'user-agent'?: string | undefined; - 'vary'?: string | undefined; - 'via'?: string | undefined; - 'warning'?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; 'www-authenticate'?: string | undefined; } - // outgoing headers allows numbers (as they are converted internally to strings) type OutgoingHttpHeader = number | string | string[]; - - interface OutgoingHttpHeaders extends NodeJS.Dict { - } - + interface OutgoingHttpHeaders extends NodeJS.Dict {} interface ClientRequestArgs { + signal?: AbortSignal | undefined; protocol?: string | null | undefined; host?: string | null | undefined; hostname?: string | null | undefined; @@ -101,16 +138,20 @@ declare module 'http' { timeout?: number | undefined; setHost?: boolean | undefined; // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 - createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; lookup?: LookupFunction | undefined; } - - interface ServerOptions { - IncomingMessage?: typeof IncomingMessage | undefined; - ServerResponse?: typeof ServerResponse | undefined; + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + IncomingMessage?: Request | undefined; + ServerResponse?: Response | undefined; /** * Optionally overrides the value of - * [`--max-http-header-size`][] for requests received by this server, i.e. + * `--max-http-header-size` for requests received by this server, i.e. * the maximum length of request headers in bytes. * @default 8192 */ @@ -122,33 +163,125 @@ declare module 'http' { * @default false */ insecureHTTPParser?: 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; } - - type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; - - class Server extends NetServer { - constructor(requestListener?: RequestListener); - constructor(options: ServerOptions, requestListener?: RequestListener); + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ setTimeout(msecs?: number, callback?: () => void): this; setTimeout(callback: () => void): this; /** * Limits maximum incoming headers count. If set to 0, no limit will be applied. - * @default 2000 - * {@link https://nodejs.org/api/http.html#http_server_maxheaderscount} + * @since v0.7.0 */ maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ timeout: number; /** - * Limit the amount of time the parser will wait to receive the complete HTTP headers. - * @default 60000 - * {@link https://nodejs.org/api/http.html#http_server_headerstimeout} + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * In case of inactivity, the rules defined in `server.timeout` apply. However, + * that inactivity based timeout would still allow the connection to be kept open + * if the headers are being sent very slowly (by default, up to a byte per 2 + * minutes). In order to prevent this, whenever header data arrives an additional + * check is made that more than `server.headersTimeout` milliseconds has not + * passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed. + * See `server.timeout` for more information on how timeout behavior can be + * customized. + * @since v11.3.0, v10.14.0 */ headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ keepAliveTimeout: number; /** - * Sets the timeout value in milliseconds for receiving the entire request from the client. - * @default 0 - * {@link https://nodejs.org/api/http.html#http_server_requesttimeout} + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 */ requestTimeout: number; addListener(event: string, listener: (...args: any[]) => void): this; @@ -156,72 +289,111 @@ declare module 'http' { addListener(event: 'connection', listener: (socket: Socket) => void): this; addListener(event: 'error', listener: (err: Error) => void): this; addListener(event: 'listening', listener: () => void): this; - addListener(event: 'checkContinue', listener: RequestListener): this; - addListener(event: 'checkExpectation', listener: RequestListener): this; + addListener(event: 'checkContinue', listener: RequestListener): this; + addListener(event: 'checkExpectation', listener: RequestListener): this; addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; - addListener(event: 'request', listener: RequestListener): this; - addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener( + event: 'connect', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: 'request', listener: RequestListener): this; + addListener( + event: 'upgrade', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; emit(event: string, ...args: any[]): boolean; emit(event: 'close'): boolean; emit(event: 'connection', socket: Socket): boolean; emit(event: 'error', err: Error): boolean; emit(event: 'listening'): boolean; - emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean; - emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit( + event: 'checkContinue', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: 'checkExpectation', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; - emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; - emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; - emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'connect', req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit( + event: 'request', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'upgrade', req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: 'close', listener: () => void): this; on(event: 'connection', listener: (socket: Socket) => void): this; on(event: 'error', listener: (err: Error) => void): this; on(event: 'listening', listener: () => void): this; - on(event: 'checkContinue', listener: RequestListener): this; - on(event: 'checkExpectation', listener: RequestListener): this; + on(event: 'checkContinue', listener: RequestListener): this; + on(event: 'checkExpectation', listener: RequestListener): this; on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; - on(event: 'request', listener: RequestListener): this; - on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'connect', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: 'close', listener: () => void): this; once(event: 'connection', listener: (socket: Socket) => void): this; once(event: 'error', listener: (err: Error) => void): this; once(event: 'listening', listener: () => void): this; - once(event: 'checkContinue', listener: RequestListener): this; - once(event: 'checkExpectation', listener: RequestListener): this; + once(event: 'checkContinue', listener: RequestListener): this; + once(event: 'checkExpectation', listener: RequestListener): this; once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; - once(event: 'request', listener: RequestListener): this; - once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once( + event: 'connect', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: 'request', listener: RequestListener): this; + once( + event: 'upgrade', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'close', listener: () => void): this; prependListener(event: 'connection', listener: (socket: Socket) => void): this; prependListener(event: 'error', listener: (err: Error) => void): this; prependListener(event: 'listening', listener: () => void): this; - prependListener(event: 'checkContinue', listener: RequestListener): this; - prependListener(event: 'checkExpectation', listener: RequestListener): this; + prependListener(event: 'checkContinue', listener: RequestListener): this; + prependListener(event: 'checkExpectation', listener: RequestListener): this; prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; - prependListener(event: 'request', listener: RequestListener): this; - prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener( + event: 'connect', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener( + event: 'upgrade', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; prependOnceListener(event: 'error', listener: (err: Error) => void): this; prependOnceListener(event: 'listening', listener: () => void): this; - prependOnceListener(event: 'checkContinue', listener: RequestListener): this; - prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; + prependOnceListener(event: 'checkContinue', listener: RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; - prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; - prependOnceListener(event: 'request', listener: RequestListener): this; - prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener( + event: 'connect', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener( + event: 'upgrade', + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; } - - // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js - class OutgoingMessage extends stream.Writable { - upgrading: boolean; + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; chunkedEncoding: boolean; shouldKeepAlive: boolean; useChunkedEncodingByDefault: boolean; @@ -230,43 +402,243 @@ declare module 'http' { * @deprecated Use `writableEnded` instead. */ finished: boolean; - headersSent: boolean; /** - * @deprecated Use `socket` instead. + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 */ - connection: Socket | null; - socket: Socket | null; - + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; constructor(); - + /** + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` 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. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.0.0 + */ getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v8.0.0 + */ getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v8.0.0 + */ hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + */ removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ flushHeaders(): void; } - - // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 - class ServerResponse extends OutgoingMessage { + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ statusMessage: string; - - constructor(req: IncomingMessage); - + constructor(req: Request); assignSocket(socket: Socket): void; detachSocket(socket: Socket): void; - // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 - // no args in writeContinue callback + /** + * Sends a HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ writeContinue(callback?: () => void): void; - writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ writeProcessing(): void; } - interface InformationEvent { statusCode: number; statusMessage: string; @@ -276,34 +648,125 @@ declare module 'http' { headers: IncomingHttpHeaders; rawHeaders: string[]; } - - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + */ aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ protocol: string; + /** + * Whether the request is send through a reused socket. + * @since v13.0.0, v12.16.0 + */ reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + * @default 2000 + */ maxHeadersCount: number; - constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); - + /** + * The request method. + * @since v0.1.97 + */ method: string; + /** + * The request path. + * @since v0.4.0 + */ path: string; - /** @deprecated since v14.1.0 Use `request.destroy()` instead. */ + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ abort(): void; onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0 + */ + getRawHeaderNames(): string[]; addListener(event: 'abort', listener: () => void): this; - addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener( + event: 'connect', + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; addListener(event: 'continue', listener: () => void): this; addListener(event: 'information', listener: (info: InformationEvent) => void): this; addListener(event: 'response', listener: (response: IncomingMessage) => void): this; addListener(event: 'socket', listener: (socket: Socket) => void): this; addListener(event: 'timeout', listener: () => void): this; - addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener( + event: 'upgrade', + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; addListener(event: 'close', listener: () => void): this; addListener(event: 'drain', listener: () => void): this; addListener(event: 'error', listener: (err: Error) => void): this; @@ -311,7 +774,6 @@ declare module 'http' { addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: 'abort', listener: () => void): this; on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; on(event: 'continue', listener: () => void): this; @@ -327,7 +789,6 @@ declare module 'http' { on(event: 'pipe', listener: (src: stream.Readable) => void): this; on(event: 'unpipe', listener: (src: stream.Readable) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: 'abort', listener: () => void): this; once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; once(event: 'continue', listener: () => void): this; @@ -343,15 +804,20 @@ declare module 'http' { once(event: 'pipe', listener: (src: stream.Readable) => void): this; once(event: 'unpipe', listener: (src: stream.Readable) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: 'abort', listener: () => void): this; - prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener( + event: 'connect', + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; prependListener(event: 'continue', listener: () => void): this; prependListener(event: 'information', listener: (info: InformationEvent) => void): this; prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; prependListener(event: 'socket', listener: (socket: Socket) => void): this; prependListener(event: 'timeout', listener: () => void): this; - prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener( + event: 'upgrade', + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; prependListener(event: 'close', listener: () => void): this; prependListener(event: 'drain', listener: () => void): this; prependListener(event: 'error', listener: (err: Error) => void): this; @@ -359,15 +825,20 @@ declare module 'http' { prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: 'abort', listener: () => void): this; - prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener( + event: 'connect', + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; prependOnceListener(event: 'continue', listener: () => void): this; prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; prependOnceListener(event: 'timeout', listener: () => void): this; - prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener( + event: 'upgrade', + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'drain', listener: () => void): this; prependOnceListener(event: 'error', listener: (err: Error) => void): this; @@ -376,45 +847,212 @@ declare module 'http' { prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ class IncomingMessage extends stream.Readable { constructor(socket: Socket); - + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ httpVersion: string; httpVersionMajor: number; httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ complete: boolean; /** - * @deprecated since v13.0.0 - Use `socket` instead. + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. */ connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket`. + * @since v0.3.0 + */ socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ trailers: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ setTimeout(msecs: number, callback?: () => void): this; /** - * Only valid for request obtained from http.Server. + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 */ method?: string | undefined; /** - * Only valid for request obtained from http.Server. + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 */ url?: string | undefined; /** - * Only valid for response obtained from http.ClientRequest. + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 */ statusCode?: number | undefined; /** - * Only valid for response obtained from http.ClientRequest. + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 */ statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ destroy(error?: Error): this; } - - interface AgentOptions { + interface AgentOptions extends Partial { /** * Keep sockets around in a pool to be used by other requests in the future. Default = false */ @@ -441,52 +1079,425 @@ declare module 'http' { */ timeout?: number | undefined; /** - * Scheduling strategy to apply when picking the next free socket to use. Default: 'fifo'. + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` */ scheduling?: 'fifo' | 'lifo' | undefined; } - + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ class Agent { + /** + * By default set to 256\. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ readonly requests: NodeJS.ReadOnlyDict; - constructor(opts?: AgentOptions); - /** * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 */ destroy(): void; } - const METHODS: string[]; - const STATUS_CODES: { [errorCode: number]: string | undefined; [errorCode: string]: string | undefined; }; - - function createServer(requestListener?: RequestListener): Server; - function createServer(options: ServerOptions, requestListener?: RequestListener): Server; - + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(options: ServerOptions, requestListener?: RequestListener): Server; // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, // create interface RequestOptions would make the naming more clear to developers - interface RequestOptions extends ClientRequestArgs { } + interface RequestOptions extends ClientRequestArgs {} + /** + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` 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. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link 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 http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - let globalAgent: Agent; + /** + * Performs the low-level validations on the provided name that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as name will result in a TypeError being thrown, identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * @param name Header name + * @since v14.3.0 + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided value that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as value will result in a TypeError being thrown. + * - Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * - Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * @param name Header name + * @param value Header value + * @since v14.3.0 + */ + function validateHeaderValue(name: string, value: string): void; + + /** + * Set the maximum number of idle HTTP parsers. Default: 1000. + * @param count + * @since v18.8.0, v16.18.0 + */ + function setMaxIdleHTTPParsers(count: number): void; + + let globalAgent: Agent; /** * Read-only property specifying the maximum allowed size of HTTP headers in bytes. - * Defaults to 16KB. Configurable using the [`--max-http-header-size`][] CLI option. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. */ const maxHeaderSize: number; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/http2.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/http2.d.ts index fe70e85dd..27c2cfa31 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/http2.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/http2.d.ts @@ -1,42 +1,41 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/http2.js) + */ declare module 'http2' { - import EventEmitter = require('events'); - import * as fs from 'fs'; - import * as net from 'net'; - import * as stream from 'stream'; - import * as tls from 'tls'; - import * as url from 'url'; - - import { - IncomingHttpHeaders as Http1IncomingHttpHeaders, - OutgoingHttpHeaders, - IncomingMessage, - ServerResponse, - } from 'http'; - export { OutgoingHttpHeaders } from 'http'; - + import EventEmitter = require('node:events'); + import * as fs from 'node:fs'; + import * as net from 'node:net'; + import * as stream from 'node:stream'; + import * as tls from 'node:tls'; + import * as url from 'node:url'; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; + export { OutgoingHttpHeaders } from 'node:http'; export interface IncomingHttpStatusHeader { - ":status"?: number | undefined; + ':status'?: number | undefined; } - export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { - ":path"?: string | undefined; - ":method"?: string | undefined; - ":authority"?: string | undefined; - ":scheme"?: string | undefined; + ':path'?: string | undefined; + ':method'?: string | undefined; + ':authority'?: string | undefined; + ':scheme'?: string | undefined; } - // Http2Stream - export interface StreamPriorityOptions { exclusive?: boolean | undefined; parent?: number | undefined; weight?: number | undefined; silent?: boolean | undefined; } - export interface StreamState { localWindowSize?: number | undefined; state?: number | undefined; @@ -45,200 +44,530 @@ declare module 'http2' { sumDependencyWeight?: number | undefined; weight?: number | undefined; } - export interface ServerStreamResponseOptions { endStream?: boolean | undefined; waitForTrailers?: boolean | undefined; } - export interface StatOptions { offset: number; length: number; } - export interface ServerStreamFileResponseOptions { statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; waitForTrailers?: boolean | undefined; offset?: number | undefined; length?: number | undefined; } - export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { onError?(err: NodeJS.ErrnoException): void; } - export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ readonly destroyed: boolean; /** - * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, - * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + * Set the `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 */ readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ readonly session: Http2Session; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ readonly state: StreamState; - + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ sendTrailers(headers: OutgoingHttpHeaders): void; - - addListener(event: "aborted", listener: () => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: "streamClosed", listener: (code: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: 'aborted', listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'streamClosed', listener: (code: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'wantTrailers', listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "aborted"): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "frameError", frameType: number, errorCode: number): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: "streamClosed", code: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "wantTrailers"): boolean; + emit(event: 'aborted'): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'frameError', frameType: number, errorCode: number): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: 'streamClosed', code: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'trailers', trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'wantTrailers'): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "aborted", listener: () => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: "streamClosed", listener: (code: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "wantTrailers", listener: () => void): this; + on(event: 'aborted', listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: 'streamClosed', listener: (code: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'wantTrailers', listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "aborted", listener: () => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: "streamClosed", listener: (code: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "wantTrailers", listener: () => void): this; + once(event: 'aborted', listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: 'streamClosed', listener: (code: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'wantTrailers', listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "aborted", listener: () => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "streamClosed", listener: (code: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: 'aborted', listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'streamClosed', listener: (code: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'wantTrailers', listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "aborted", listener: () => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: 'aborted', listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'streamClosed', listener: (code: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'wantTrailers', listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface ClientHttp2Stream extends Http2Stream { - addListener(event: "continue", listener: () => {}): this; - addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'continue', listener: () => {}): this; + addListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "continue"): boolean; - emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'continue'): boolean; + emit(event: 'headers', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'push', headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'response', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "continue", listener: () => {}): this; - on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'continue', listener: () => {}): this; + on(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "continue", listener: () => {}): this; - once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'continue', listener: () => {}): this; + once(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "continue", listener: () => {}): this; - prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'continue', listener: () => {}): this; + prependListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "continue", listener: () => {}): this; - prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'continue', listener: () => {}): this; + prependOnceListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; } - // Http2Session - export interface Settings { headerTableSize?: number | undefined; enablePush?: boolean | undefined; @@ -248,15 +577,14 @@ declare module 'http2' { maxHeaderListSize?: number | undefined; enableConnectProtocol?: boolean | undefined; } - export interface ClientSessionRequestOptions { endStream?: boolean | undefined; exclusive?: boolean | undefined; parent?: number | undefined; weight?: number | undefined; waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; } - export interface SessionState { effectiveLocalWindowSize?: number | undefined; effectiveRecvDataLength?: number | undefined; @@ -268,170 +596,444 @@ declare module 'http2' { deflateDynamicTableSize?: number | undefined; inflateDynamicTableSize?: number | undefined; } - export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ readonly type: number; - + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0 + */ setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ setTimeout(msecs: number, callback?: () => void): void; - settings(settings: Settings): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings(settings: Settings, callback?: (err: Error | null, settings: Settings, duration: number) => void): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ unref(): void; - - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - addListener(event: "localSettings", listener: (settings: Settings) => void): this; - addListener(event: "ping", listener: () => void): this; - addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - addListener(event: "timeout", listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: 'localSettings', listener: (settings: Settings) => void): this; + addListener(event: 'ping', listener: () => void): this; + addListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + addListener(event: 'timeout', listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; - emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; - emit(event: "localSettings", settings: Settings): boolean; - emit(event: "ping"): boolean; - emit(event: "remoteSettings", settings: Settings): boolean; - emit(event: "timeout"): boolean; + emit(event: 'close'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'frameError', frameType: number, errorCode: number, streamID: number): boolean; + emit(event: 'goaway', errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: 'localSettings', settings: Settings): boolean; + emit(event: 'ping'): boolean; + emit(event: 'remoteSettings', settings: Settings): boolean; + emit(event: 'timeout'): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - on(event: "localSettings", listener: (settings: Settings) => void): this; - on(event: "ping", listener: () => void): this; - on(event: "remoteSettings", listener: (settings: Settings) => void): this; - on(event: "timeout", listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: 'localSettings', listener: (settings: Settings) => void): this; + on(event: 'ping', listener: () => void): this; + on(event: 'remoteSettings', listener: (settings: Settings) => void): this; + on(event: 'timeout', listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - once(event: "localSettings", listener: (settings: Settings) => void): this; - once(event: "ping", listener: () => void): this; - once(event: "remoteSettings", listener: (settings: Settings) => void): this; - once(event: "timeout", listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: 'localSettings', listener: (settings: Settings) => void): this; + once(event: 'ping', listener: () => void): this; + once(event: 'remoteSettings', listener: (settings: Settings) => void): this; + once(event: 'timeout', listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependListener(event: "ping", listener: () => void): this; - prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependListener(event: "timeout", listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'ping', listener: () => void): this; + prependListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'timeout', listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "ping", listener: () => void): this; - prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'ping', listener: () => void): this; + prependOnceListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; - - addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - addListener(event: "origin", listener: (origins: string[]) => void): this; - addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: 'origin', listener: (origins: string[]) => void): this; + addListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; - emit(event: "origin", origins: ReadonlyArray): boolean; - emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'altsvc', alt: string, origin: string, stream: number): boolean; + emit(event: 'origin', origins: ReadonlyArray): boolean; + emit(event: 'connect', session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - on(event: "origin", listener: (origins: string[]) => void): this; - on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + on(event: 'origin', listener: (origins: string[]) => void): this; + on(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - once(event: "origin", listener: (origins: string[]) => void): this; - once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + once(event: 'origin', listener: (origins: string[]) => void): this; + once(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependListener(event: "origin", listener: (origins: string[]) => void): this; - prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: 'origin', listener: (origins: string[]) => void): this; + prependListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; - prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: 'origin', listener: (origins: string[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface AlternativeServiceOptions { origin: number | string | url.URL; } - export interface ServerHttp2Session extends Http2Session { readonly server: Http2Server | Http2SecureServer; - + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; - origin(...args: Array): void; - - addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'connect', session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - // Http2Server - export interface SessionOptions { maxDeflateDynamicTableSize?: number | undefined; maxSessionMemory?: number | undefined; @@ -441,296 +1043,734 @@ declare module 'http2' { paddingStrategy?: number | undefined; peerMaxConcurrentStreams?: number | undefined; settings?: Settings | undefined; - + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; selectPadding?(frameLen: number, maxFrameLen: number): number; createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; } - export interface ClientSessionOptions extends SessionOptions { maxReservedRemoteStreams?: number | undefined; createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; protocol?: 'http:' | 'https:' | undefined; } - export interface ServerSessionOptions extends SessionOptions { Http1IncomingMessage?: typeof IncomingMessage | undefined; Http1ServerResponse?: typeof ServerResponse | undefined; Http2ServerRequest?: typeof Http2ServerRequest | undefined; Http2ServerResponse?: typeof Http2ServerResponse | undefined; } - - export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } - export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } - - export interface ServerOptions extends ServerSessionOptions { } - + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} export interface SecureServerOptions extends SecureServerSessionOptions { allowHTTP1?: boolean | undefined; origins?: string[] | undefined; } - - export interface Http2Server extends net.Server { - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "session", session: ServerHttp2Session): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "session", listener: (session: ServerHttp2Session) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "session", listener: (session: ServerHttp2Session) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - + interface HTTP2ServerCommon { setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; } - - export interface Http2SecureServer extends tls.Server { - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "session", session: ServerHttp2Session): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "session", listener: (session: ServerHttp2Session) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "session", listener: (session: ServerHttp2Session) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - setTimeout(msec?: number, callback?: () => void): this; } - + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'unknownProtocol', socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ export class Http2ServerRequest extends stream.Readable { constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); - + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ readonly httpVersion: string; readonly httpVersionMinor: number; readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ url: string; - + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ setTimeout(msecs: number, callback?: () => void): void; read(size?: number): Buffer | string | null; - - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "aborted", hadError: boolean, code: number): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; + emit(event: 'aborted', hadError: boolean, code: number): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'end'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'error', err: Error): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; + on(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; + once(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ export class Http2ServerResponse extends stream.Writable { constructor(stream: ServerHttp2Stream); - + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ statusMessage: ''; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ end(callback?: () => void): this; end(data: string | Uint8Array, callback?: () => void): this; end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` 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_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ setHeader(name: string, value: number | string | ReadonlyArray): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses_must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * 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 free again. + * @since v8.4.0 + */ write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ writeContinue(): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; - - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - - // Public API - export namespace constants { const NGHTTP2_SESSION_SERVER: number; const NGHTTP2_SESSION_CLIENT: number; @@ -941,17 +1981,117 @@ declare module 'http2' { const HTTP_STATUS_NOT_EXTENDED: number; const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; } - + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ export function getUnpackedSettings(buf: Uint8Array): Settings; - + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; export function connect( authority: string | url.URL, diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/https.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/https.d.ts index 332bf6cd5..0519f2630 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/https.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/https.d.ts @@ -1,54 +1,105 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * 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/v16.9.0/lib/https.js) + */ declare module 'https' { - import { Duplex } from 'stream'; - import * as tls from 'tls'; - 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 | undefined; // Defaults to true - servername?: string | undefined; // 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; + 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 | 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 { constructor(options?: AgentOptions); options: AgentOptions; } - - interface Server extends http.Server {} - 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 {} + /** + * 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); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); 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: '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): this; - addListener(event: 'checkExpectation', listener: http.RequestListener): this; + addListener(event: 'checkContinue', listener: http.RequestListener): this; + addListener(event: 'checkExpectation', listener: http.RequestListener): this; addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - addListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; - addListener(event: 'request', listener: http.RequestListener): this; - addListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener( + event: 'connect', + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener( + event: 'upgrade', + listener: (req: InstanceType, 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: '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; @@ -56,88 +107,427 @@ declare module 'https' { emit(event: 'connection', socket: Duplex): boolean; emit(event: 'error', err: Error): boolean; emit(event: 'listening'): boolean; - emit(event: 'checkContinue', req: http.IncomingMessage, res: http.ServerResponse): boolean; - emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit( + event: 'checkContinue', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: 'checkExpectation', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; emit(event: 'clientError', err: Error, socket: Duplex): boolean; - emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; - emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; - emit(event: 'upgrade', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'connect', req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: 'request', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'upgrade', req: InstanceType, 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: '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): this; - on(event: 'checkExpectation', listener: http.RequestListener): this; + on(event: 'checkContinue', listener: http.RequestListener): this; + on(event: 'checkExpectation', listener: http.RequestListener): this; on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - on(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; - on(event: 'request', listener: http.RequestListener): this; - on(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: InstanceType, 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: '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): this; - once(event: 'checkExpectation', listener: http.RequestListener): this; + once(event: 'checkContinue', listener: http.RequestListener): this; + once(event: 'checkExpectation', listener: http.RequestListener): this; once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - once(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; - once(event: 'request', listener: http.RequestListener): this; - once(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'connect', listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: InstanceType, 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: '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): this; - prependListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependListener(event: 'checkContinue', listener: http.RequestListener): this; + prependListener(event: 'checkExpectation', listener: http.RequestListener): this; prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - prependListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; - prependListener(event: 'request', listener: http.RequestListener): this; - prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener( + event: 'connect', + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener( + event: 'upgrade', + listener: (req: InstanceType, 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: '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): this; - prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; - prependOnceListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; - prependOnceListener(event: 'request', listener: http.RequestListener): this; - prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener( + event: 'connect', + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener( + event: 'upgrade', + listener: (req: InstanceType, 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('https'); + * const fs = require('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('https'); + * const fs = require('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): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * 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('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('tls'); + * const https = require('https'); + * const crypto = require('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-sha25 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('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' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/module.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/module.d.ts index 6688ba6e6..74dd41a54 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/module.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/module.d.ts @@ -1,15 +1,53 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * @since v0.3.7 + */ declare module 'module' { - import { URL } from 'url'; + import { URL } from 'node:url'; 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('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('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 + */ function findSourceMap(path: string, error?: Error): SourceMap; interface SourceMapPayload { file: string; @@ -20,7 +58,6 @@ declare module 'module' { mappings: string; sourceRoot: string; } - interface SourceMapping { generatedLine: number; generatedColumn: number; @@ -28,10 +65,20 @@ declare module 'module' { originalLine: number; originalColumn: 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); + /** + * Given a line number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ findEntry(line: number, column: number): SourceMapping; } } @@ -39,18 +86,30 @@ declare module 'module' { class Module { static runMain(): void; 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; - constructor(id: string, parent?: Module); } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } export = Module; } declare module 'node:module' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/net.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/net.d.ts index 733c6c286..5defb606f 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/net.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/net.d.ts @@ -1,30 +1,37 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * > Stability: 2 - Stable + * + * The `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('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/net.js) + */ declare module 'net' { - import * as stream from 'stream'; - import EventEmitter = require('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.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; interface AddressInfo { address: string; family: string; port: number; } - interface SocketConstructorOpts { fd?: number | undefined; allowHalfOpen?: boolean | undefined; readable?: boolean | undefined; writable?: boolean | undefined; + signal?: AbortSignal; } - interface OnReadOpts { buffer: Uint8Array | (() => Uint8Array); /** @@ -34,7 +41,6 @@ declare module 'net' { */ callback(bytesWritten: number, buf: Uint8Array): boolean; } - interface ConnectOpts { /** * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. @@ -43,7 +49,6 @@ declare module 'net' { */ onread?: OnReadOpts | undefined; } - interface TcpSocketConnectOpts extends ConnectOpts { port: number; host?: string | undefined; @@ -52,53 +57,269 @@ declare module 'net' { hints?: number | undefined; family?: number | undefined; lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: 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 + /** + * 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; connect(port: number, host: string, connectionListener?: () => void): this; connect(port: number, 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; + /** + * 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 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; + /** + * See `writable.destroyed` for further details. + */ readonly destroyed: boolean; - readonly localAddress: string; - readonly localPort: number; + /** + * 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 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 v10.16.0 + */ + readonly pending: boolean; + /** + * This property represents the state of the connection as a string. + * @see {https://nodejs.org/api/net.html#socketreadystate} + * @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'`. + * @since v0.11.14 + */ readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ readonly remotePort?: number | undefined; - - // Extended base methods - end(cb?: () => void): this; - end(buffer: Uint8Array | string, cb?: () => void): this; - end(str: Uint8Array | string, encoding?: BufferEncoding, cb?: () => void): this; - + /** + * 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 * 1. close @@ -111,73 +332,67 @@ declare module 'net' { * 8. timeout */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => 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: "ready", listener: () => void): this; - addListener(event: "timeout", listener: () => void): this; - + addListener(event: 'close', listener: (hadError: boolean) => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'data', listener: (data: Buffer) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => 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: '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: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "ready"): boolean; - emit(event: "timeout"): boolean; - + emit(event: 'close', hadError: boolean): boolean; + emit(event: 'connect'): boolean; + emit(event: 'data', data: Buffer): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): 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: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => 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: "ready", listener: () => void): this; - on(event: "timeout", listener: () => void): this; - + on(event: 'close', listener: (hadError: boolean) => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'data', listener: (data: Buffer) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => 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: '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: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => 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: "ready", listener: () => void): this; - once(event: "timeout", listener: () => void): this; - + once(event: 'close', listener: (hadError: boolean) => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'data', listener: (data: Buffer) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => 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: '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: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => 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: "ready", listener: () => void): this; - prependListener(event: "timeout", listener: () => void): this; - + prependListener(event: 'close', listener: (hadError: boolean) => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'data', listener: (data: Buffer) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => 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: '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: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => 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: "ready", listener: () => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'data', listener: (data: Buffer) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => 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: 'ready', listener: () => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; } - - interface ListenOptions { + interface ListenOptions extends Abortable { port?: number | undefined; host?: string | undefined; backlog?: number | undefined; @@ -190,26 +405,85 @@ declare module 'net' { */ ipv6Only?: boolean | undefined; } - 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; } - - // https://github.com/nodejs/node/blob/master/lib/net.js + /** + * 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?: 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.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; listen(port?: number, hostname?: string, listeningListener?: () => void): this; listen(port?: number, backlog?: number, listeningListener?: () => void): this; @@ -219,15 +493,79 @@ declare module 'net' { listen(options: ListenOptions, listeningListener?: () => void): this; listen(handle: any, backlog?: number, 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; - /** * events.EventEmitter * 1. close @@ -236,63 +574,257 @@ declare module 'net' { * 4. listening */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + } + 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 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.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 + * @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 + * @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 + * @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 | undefined; } - interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { 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 an TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('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`: + * + * ```console + * $ 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: + * + * ```console + * $ 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?: 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; + /** + * Tests if input is an IP address. Returns `0` for invalid strings, + * returns `4` for IP version 4 addresses, and returns `6` for IP version 6 + * addresses. + * @since v0.3.0 + */ function isIP(input: string): number; + /** + * Returns `true` if input is a version 4 IP address, otherwise returns `false`. + * @since v0.3.0 + */ function isIPv4(input: string): boolean; + /** + * Returns `true` if input is a version 6 IP address, otherwise 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 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * @since v15.14.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0 + */ + readonly port: number; + /** + * @since v15.14.0 + */ + readonly flowlabel: number; + } } declare module 'node:net' { export * from 'net'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/os.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/os.d.ts index 9639dce06..162ed4239 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/os.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/os.d.ts @@ -1,6 +1,15 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/os.js) + */ declare module 'os' { interface CpuInfo { model: string; @@ -13,7 +22,6 @@ declare module 'os' { irq: number; }; } - interface NetworkInterfaceBase { address: string; netmask: string; @@ -21,16 +29,13 @@ declare module 'os' { internal: boolean; cidr: string | null; } - interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: "IPv4"; + family: 'IPv4'; } - interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: "IPv6"; + family: 'IPv6'; scopeid: number; } - interface UserInfo { username: T; uid: number; @@ -38,26 +43,197 @@ declare module 'os' { shell: T; 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 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. + * @since v0.3.3 + */ function cpus(): CpuInfo[]; + /** + * 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; + /** + * 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; + /** + * 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; function userInfo(options?: { encoding: BufferEncoding }): UserInfo; - type SignalConstants = { [key in NodeJS.Signals]: number; }; - namespace constants { const UV_UDP_REUSEADDR: number; namespace signals {} @@ -210,34 +386,71 @@ declare module 'os' { const PRIORITY_HIGHEST: 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'`, `'s390'`, `'s390x'`, `'x32'`, 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; - function platform(): NodeJS.Platform; - function tmpdir(): string; - const EOL: string; - function endianness(): "BE" | "LE"; /** - * Gets the priority of a process. - * Defaults to current process. + * Returns a string identifying the operating system platform. 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 operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): 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'; + /** + * 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' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/path.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/path.d.ts index efe1c90e7..93e868779 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/path.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/path.d.ts @@ -1,6 +1,23 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/path.js) + */ declare module 'path' { namespace path { /** @@ -28,7 +45,6 @@ declare module 'path' { */ name: string; } - interface FormatInputPathObject { /** * The root of the path such as '/' or 'c:\' @@ -51,24 +67,24 @@ declare module 'path' { */ name?: string | undefined; } - interface PlatformPath { /** * Normalize a string path, reducing '..' and '.' parts. * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. * - * @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}. * * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * @@ -77,61 +93,71 @@ declare module 'path' { * the current working directory is used as well. The resulting path is normalized, * and trailing slashes are removed unless the path gets resolved to the root directory. * - * @param pathSegments string paths to join. Non-string arguments are ignored. + * @param paths string paths to join. + * @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. */ relative(from: string, to: string): string; /** * Return the directory name of a path. Similar to the Unix dirname command. * - * @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; /** * Return the last portion of a path. Similar to the Unix basename command. * Often used to extract the file name from a fully qualified path. * - * @param p the path to evaluate. + * @param path the path to evaluate. * @param ext 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, ext?: 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; /** * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. * If path is not a string, path will be returned without modifications. @@ -158,3 +184,11 @@ 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; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/perf_hooks.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/perf_hooks.d.ts index 23b899324..00a7eb649 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/perf_hooks.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/perf_hooks.d.ts @@ -1,41 +1,46 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * 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/) + * + * ```js + * const { PerformanceObserver, performance } = require('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/v16.9.0/lib/perf_hooks.js) + */ declare module 'perf_hooks' { - import { AsyncResource } from 'async_hooks'; - + import { AsyncResource } from 'node:async_hooks'; type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; - - interface PerformanceEntry { - /** - * The total number of milliseconds elapsed for this entry. - * This value will not be meaningful for all Performance Entry types. - */ - readonly duration: number; - - /** - * The name of the performance entry. - */ - readonly name: string; - - /** - * The high resolution millisecond timestamp marking the starting time of the Performance Entry. - */ - readonly startTime: number; - - /** - * The type of the performance entry. - * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. - */ - readonly entryType: EntryType; - + interface NodeGCPerformanceDetail { /** * 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. @@ -43,50 +48,145 @@ declare module 'perf_hooks' { */ readonly flags?: number | undefined; } - - interface PerformanceNodeTiming extends PerformanceEntry { + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); /** - * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + * 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. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * 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; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + } + /** + * _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 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 { idle: number; active: number; utilization: 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 { /** * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. @@ -94,7 +194,35 @@ declare module 'perf_hooks' { * @param name */ 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. * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', @@ -102,8 +230,7 @@ declare module 'perf_hooks' { * Performance marks are used to mark specific significant moments in the Performance Timeline. * @param name */ - mark(name?: string): void; - + mark(name?: string, options?: MarkOptions): void; /** * Creates a new PerformanceMeasure entry in the Performance Timeline. * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', @@ -120,84 +247,201 @@ declare module 'perf_hooks' { * @param endMark */ measure(name: string, startMark?: string, endMark?: string): void; - + measure(name: string, options: MeasureOptions): void; /** * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. */ readonly nodeTiming: PerformanceNodeTiming; - /** * @return the current high resolution millisecond timestamp */ now(): number; - /** * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. */ readonly timeOrigin: number; - /** * Wraps a function within a new function that measures the running time of the wrapped function. * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. * @param fn */ - timerify any>(fn: T): T; - + timerify any>(fn: T, options?: TimerifyOptions): T; /** * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). * 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('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 + * * } + * * ] + * + * 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('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')); // [] + * 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('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 + * * } + * * ] + * + * 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; - 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('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called three times synchronously. `list` contains one item. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 */ - observe(options: { entryTypes: ReadonlyArray; buffered?: boolean | undefined }): void; + observe( + options: + | { + entryTypes: ReadonlyArray; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + } + ): void; } - namespace constants { const NODE_PERFORMANCE_GC_MAJOR: number; const NODE_PERFORMANCE_GC_MINOR: number; const NODE_PERFORMANCE_GC_INCREMENTAL: number; const NODE_PERFORMANCE_GC_WEAKCB: number; - const NODE_PERFORMANCE_GC_FLAGS_NO: number; const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; @@ -206,9 +450,7 @@ declare module 'perf_hooks' { const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; } - const performance: Performance; - interface EventLoopMonitorOptions { /** * The sampling rate in milliseconds. @@ -217,60 +459,130 @@ declare module 'perf_hooks' { */ 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 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + 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. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 */ enable(): boolean; /** - * Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 */ disable(): boolean; - - /** - * Resets the collected histogram data. - */ - reset(): void; - - /** - * Returns the value at the given percentile. - * @param percentile A percentile value between 1 and 100. - */ - percentile(percentile: number): number; - - /** - * A `Map` object detailing the accumulated percentile distribution. - */ - readonly percentiles: Map; - - /** - * The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. - */ - readonly exceeds: number; - - /** - * The minimum recorded event loop delay. - */ - readonly min: number; - - /** - * The maximum recorded event loop delay. - */ - readonly max: number; - - /** - * The mean of the recorded event loop delays. - */ - readonly mean: number; - - /** - * The standard deviation of the recorded event loop delays. - */ - readonly stddev: number; } - - function monitorEventLoopDelay(options?: EventLoopMonitorOptions): EventLoopDelayMonitor; + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * 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 + */ + recordDelta(): 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('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 minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + 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; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; } declare module 'node:perf_hooks' { export * from 'perf_hooks'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/process.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/process.d.ts index bf7386200..ecf401022 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/process.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/process.d.ts @@ -2,18 +2,27 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ declare module 'process' { - import * as tty from 'tty'; - + import * as tty from 'node:tty'; + import { Worker } from 'node:worker_threads'; global { var process: NodeJS.Process; - namespace NodeJS { // this namespace merge is here because these are specifically used // as the type for process.stdin, process.stdout, and process.stderr. // they can't live in tty.d.ts because we need to disambiguate the imported name. interface ReadStream extends tty.ReadStream {} interface WriteStream extends tty.WriteStream {} - + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } interface MemoryUsage { rss: number; heapTotal: number; @@ -21,12 +30,10 @@ declare module 'process' { external: number; arrayBuffers: number; } - interface CpuUsage { user: number; system: number; } - interface ProcessRelease { name: string; sourceUrl?: string | undefined; @@ -34,7 +41,6 @@ declare module 'process' { libUrl?: string | undefined; lts?: string | undefined; } - interface ProcessVersions extends Dict { http_parser: string; node: string; @@ -45,52 +51,76 @@ declare module 'process' { modules: string; openssl: string; } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin' - | 'netbsd'; - + type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - + | 'SIGABRT' + | 'SIGALRM' + | 'SIGBUS' + | 'SIGCHLD' + | 'SIGCONT' + | 'SIGFPE' + | 'SIGHUP' + | 'SIGILL' + | 'SIGINT' + | 'SIGIO' + | 'SIGIOT' + | 'SIGKILL' + | 'SIGPIPE' + | 'SIGPOLL' + | 'SIGPROF' + | 'SIGPWR' + | 'SIGQUIT' + | 'SIGSEGV' + | 'SIGSTKFLT' + | 'SIGSTOP' + | 'SIGSYS' + | 'SIGTERM' + | 'SIGTRAP' + | 'SIGTSTP' + | 'SIGTTIN' + | 'SIGTTOU' + | 'SIGUNUSED' + | 'SIGURG' + | 'SIGUSR1' + | 'SIGUSR2' + | 'SIGVTALRM' + | 'SIGWINCH' + | 'SIGXCPU' + | 'SIGXFSZ' + | 'SIGBREAK' + | 'SIGLOST' + | 'SIGINFO'; type UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'; type MultipleResolveType = 'resolve' | 'reject'; - type BeforeExitListener = (code: number) => void; type DisconnectListener = () => void; type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; + type RejectionHandledListener = (promise: Promise) => void; type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume the the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; + type WorkerListener = (worker: Worker) => void; interface Socket extends ReadWriteStream { isTTY?: true | undefined; } - // Alias for compatibility - interface ProcessEnv extends Dict {} - + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } interface HRTime { (time?: [number, number]): [number, number]; bigint(): bigint; } - interface ProcessReport { /** * Directory where the report is written. @@ -98,7 +128,6 @@ declare module 'process' { * @default '' indicating that reports are written to the current */ directory: string; - /** * Filename where the report is written. * The default value is the empty string. @@ -106,39 +135,33 @@ declare module 'process' { * PID, and sequence number. */ filename: string; - /** * Returns a JSON-formatted diagnostic report for the running process. * The report's JavaScript stack trace is taken from err, if present. */ getReport(err?: Error): string; - /** * If true, a diagnostic report is generated on fatal errors, * such as out of memory errors or failed C++ assertions. * @default false */ reportOnFatalError: boolean; - /** * If true, a diagnostic report is generated when the process * receives the signal specified by process.report.signal. * @default false */ reportOnSignal: boolean; - /** * If true, a diagnostic report is generated on uncaught exception. * @default false */ reportOnUncaughtException: boolean; - /** * The signal used to trigger the creation of a diagnostic report. * @default 'SIGUSR2' */ signal: Signals; - /** * Writes a diagnostic report to a file. If filename is not provided, the default filename * includes the date, time, PID, and a sequence number. @@ -155,7 +178,6 @@ declare module 'process' { writeReport(error?: Error): string; writeReport(fileName?: string, err?: Error): string; } - interface ResourceUsage { fsRead: number; fsWrite: number; @@ -174,88 +196,1039 @@ declare module 'process' { userCPUTime: number; voluntaryContextSwitches: number; } - + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } interface Process extends EventEmitter { /** - * Can also be a tty.WriteStream, not typed due to limitations. + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. */ stdout: WriteStream & { fd: 1; }; /** - * Can also be a tty.WriteStream, not typed due to limitations. + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. */ stderr: WriteStream & { fd: 2; }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ stdin: ReadStream & { fd: 0; }; openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit_before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ getgid(): number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ setgid(id: number | string): void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ getuid(): number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ setuid(id: number | string): void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ geteuid(): number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ seteuid(id: number | string): void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ getegid(): number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ setegid(id: number | string): void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ getgroups(): number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ setgroups(groups: ReadonlyArray): void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ hasUncaughtExceptionCaptureCallback(): boolean; - version: string; - versions: ProcessVersions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ kill(pid: number, signal?: string | number): true; - pid: number; - ppid: number; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ title: string; - arch: string; - platform: Platform; - /** @deprecated since v14.0.0 - use `require.main` instead. */ + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: string; + /** + * The `process.platform` property returns a string identifying the operating + * system platform on which the Node.js process is running. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ mainModule?: Module | undefined; - memoryUsage(): MemoryUsage; + memoryUsage: MemoryUsageFn; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; features: { inspector: boolean; debug: boolean; @@ -267,147 +1240,242 @@ declare module 'process' { tls: boolean; }; /** - * @deprecated since v14.0.0 - Calling process.umask() with no argument causes - * the process-wide umask to be written twice. This introduces a race condition between threads, - * and is a potential security vulnerability. There is no safe, cross-platform alternative API. + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. */ umask(): number; /** * Can only be set if not in worker thread. */ umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ uptime(): number; hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean | undefined}, callback?: (error: Error | null) => void): boolean; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ connected: boolean; - /** * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 */ allowedNodeEnvironmentFlags: ReadonlySet; - /** - * Only available with `--experimental-report` + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 */ report?: ProcessReport | undefined; - + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ resourceUsage(): ResourceUsage; - + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ traceDeprecation: boolean; - /* EventEmitter */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; + addListener(event: 'beforeExit', listener: BeforeExitListener): this; + addListener(event: 'disconnect', listener: DisconnectListener): this; + addListener(event: 'exit', listener: ExitListener): this; + addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + addListener(event: 'warning', listener: WarningListener): this; + addListener(event: 'message', listener: MessageListener): this; addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "uncaughtExceptionMonitor", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; + addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + addListener(event: 'worker', listener: WorkerListener): this; + emit(event: 'beforeExit', code: number): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'exit', code: number): boolean; + emit(event: 'rejectionHandled', promise: Promise): boolean; + emit(event: 'uncaughtException', error: Error): boolean; + emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; + emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; + emit(event: 'warning', warning: Error): boolean; + emit(event: 'message', message: unknown, sendHandle: unknown): this; emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; + emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; + emit(event: 'worker', listener: WorkerListener): this; + on(event: 'beforeExit', listener: BeforeExitListener): this; + on(event: 'disconnect', listener: DisconnectListener): this; + on(event: 'exit', listener: ExitListener): this; + on(event: 'rejectionHandled', listener: RejectionHandledListener): this; + on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + on(event: 'warning', listener: WarningListener): this; + on(event: 'message', listener: MessageListener): this; on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: 'multipleResolves', listener: MultipleResolveListener): this; + on(event: 'worker', listener: WorkerListener): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; + once(event: 'beforeExit', listener: BeforeExitListener): this; + once(event: 'disconnect', listener: DisconnectListener): this; + once(event: 'exit', listener: ExitListener): this; + once(event: 'rejectionHandled', listener: RejectionHandledListener): this; + once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + once(event: 'warning', listener: WarningListener): this; + once(event: 'message', listener: MessageListener): this; once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; + once(event: 'multipleResolves', listener: MultipleResolveListener): this; + once(event: 'worker', listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependListener(event: 'disconnect', listener: DisconnectListener): this; + prependListener(event: 'exit', listener: ExitListener): this; + prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependListener(event: 'warning', listener: WarningListener): this; + prependListener(event: 'message', listener: MessageListener): this; prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; + prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependListener(event: 'worker', listener: WorkerListener): this; + prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; + prependOnceListener(event: 'exit', listener: ExitListener): this; + prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependOnceListener(event: 'warning', listener: WarningListener): this; + prependOnceListener(event: 'message', listener: MessageListener): this; prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; + prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependOnceListener(event: 'worker', listener: WorkerListener): this; + listeners(event: 'beforeExit'): BeforeExitListener[]; + listeners(event: 'disconnect'): DisconnectListener[]; + listeners(event: 'exit'): ExitListener[]; + listeners(event: 'rejectionHandled'): RejectionHandledListener[]; + listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; + listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; + listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; + listeners(event: 'warning'): WarningListener[]; + listeners(event: 'message'): MessageListener[]; listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - interface Global { - process: Process; + listeners(event: 'multipleResolves'): MultipleResolveListener[]; + listeners(event: 'worker'): WorkerListener[]; } } } - export = process; } declare module 'node:process' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/querystring.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/querystring.d.ts index db101dfa9..38f687d11 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/querystring.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/querystring.d.ts @@ -1,22 +1,98 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('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/v16.9.0/lib/querystring.js) + */ declare module 'querystring' { interface StringifyOptions { encodeURIComponent?: ((str: string) => string) | undefined; } - interface ParseOptions { maxKeys?: number | undefined; decodeURIComponent?: ((str: string) => string) | undefined; } - - interface ParsedUrlQuery extends NodeJS.Dict { } - - interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> { - } - + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | 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; /** * The querystring.encode() function is an alias for querystring.stringify(). @@ -26,7 +102,31 @@ declare module 'querystring' { * The querystring.decode() function is an alias for querystring.parse(). */ 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' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/readline.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/readline.d.ts index e0f6909b3..e47ac3b29 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/readline.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/readline.d.ts @@ -1,9 +1,38 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. It can be accessed + * using: + * + * ```js + * const readline = require('readline'); + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * + * rl.question('What do you think of Node.js? ', (answer) => { + * // TODO: Log the answer in a database + * 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/v16.9.0/lib/readline.js) + */ declare module 'readline' { - import EventEmitter = require('events'); - + import { Abortable, EventEmitter } from 'node:events'; interface Key { sequence?: string | undefined; name?: string | undefined; @@ -11,17 +40,56 @@ declare module 'readline' { meta?: boolean | undefined; shift?: boolean | undefined; } - + /** + * 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 + */ 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; - /** * NOTE: According to the documentation: * @@ -40,23 +108,145 @@ declare module 'readline' { * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface */ protected constructor(options: ReadLineOptions); - + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.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 `readline.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 `readline.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 `readline.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. + * + * 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); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @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 `readline.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 `readline.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 `readline.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 `readline.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; - /** * events.EventEmitter * 1. close @@ -66,109 +256,288 @@ declare module 'readline' { * 5. SIGCONT * 6. SIGINT * 7. SIGTSTP + * 8. history */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'history', listener: (history: string[]) => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'history', history: string[]): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', 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; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', 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; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', 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; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'history', listener: (history: string[]) => void): this; [Symbol.asyncIterator](): AsyncIterableIterator; } - type ReadLine = Interface; // type forwarded for backwards compatibility - type Completer = (line: string) => CompleterResult; - type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => any; - + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; type CompleterResult = [string[], string]; - interface ReadLineOptions { input: NodeJS.ReadableStream; 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; } - + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('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 `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; 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); + * ``` + * @since v0.7.7 + */ function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; - type Direction = -1 | 0 | 1; - 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; /** - * 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; /** - * 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; /** - * 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`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('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('fs'); + * const readline = require('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('fs'); + * const readline = require('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('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('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 + * @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; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/stream.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/stream.d.ts index a8260411f..d32cbf9ce 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/stream.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/stream.d.ts @@ -1,55 +1,418 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/stream.js) + */ declare module 'stream' { - import EventEmitter = require('events'); - + import { EventEmitter, Abortable } from 'node:events'; + import { Blob as NodeBlob } from 'node:buffer'; + import * as streamPromises from 'node:stream/promises'; + import * as streamConsumers from 'node:stream/consumers'; class internal extends EventEmitter { - pipe(destination: T, options?: { end?: boolean | undefined; }): T; + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; } - namespace internal { class Stream extends internal { constructor(opts?: ReadableOptions); } - - interface ReadableOptions { + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; highWaterMark?: number | undefined; - encoding?: BufferEncoding | undefined; objectMode?: boolean | undefined; - read?(this: Readable, size: number): void; - destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; autoDestroy?: boolean | undefined; } - + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ class Readable extends Stream implements NodeJS.ReadableStream { /** * A utility method for creating Readable Streams out of iterators. */ static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; - + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ destroyed: boolean; constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; _read(size: number): void; + /** + * The `readable.read()` method pulls some data out of the internal buffer and + * returns it. If no data available to be read, `null` is returned. By default, + * the data will be returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.match(/\n\n/)) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * } else { + * // Still reading the header. + * header += str; + * } + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ unshift(chunk: any, encoding?: BufferEncoding): void; - wrap(oldStream: NodeJS.ReadableStream): this; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: BufferEncoding): boolean; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ destroy(error?: Error): this; - /** * Event emitter * The defined events on documents including: @@ -61,109 +424,294 @@ declare module 'stream' { * 6. readable * 7. resume */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: any) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "data", chunk: any): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "pause"): boolean; - emit(event: "readable"): boolean; - emit(event: "resume"): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: any) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "resume", listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: any) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "resume", listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: any) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: any) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: any) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "pause", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "resume", listener: () => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - [Symbol.asyncIterator](): AsyncIterableIterator; } - - interface WritableOptions { - highWaterMark?: number | undefined; + interface WritableOptions extends StreamOptions { decodeStrings?: boolean | undefined; defaultEncoding?: BufferEncoding | undefined; - objectMode?: boolean | undefined; - emitClose?: boolean | undefined; write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?(this: Writable, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; - destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; final?(this: Writable, callback: (error?: Error | null) => void): void; - autoDestroy?: boolean | undefined; } - + /** + * @since v0.9.4 + */ class Writable extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ destroyed: boolean; constructor(opts?: WritableOptions); _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; - write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * It is recommended that once `write()` returns false, no more chunks be written + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @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`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ end(cb?: () => void): this; end(chunk: any, cb?: () => void): this; end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, it is recommended that calls to `writable.uncork()` be + * deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ destroy(error?: Error): this; - /** * Event emitter * The defined events on documents including: @@ -174,63 +722,56 @@ declare module 'stream' { * 5. pipe * 6. unpipe */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } - interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean | undefined; readableObjectMode?: boolean | undefined; @@ -238,14 +779,30 @@ declare module 'stream' { readableHighWaterMark?: number | undefined; writableHighWaterMark?: number | undefined; writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; read?(this: Duplex, size: number): void; write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; final?(this: Duplex, callback: (error?: Error | null) => void): void; destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; } - - // Note: Duplex extends both Readable and Writable. + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ class Duplex extends Readable implements Writable { readonly writable: boolean; readonly writableEnded: boolean; @@ -254,10 +811,47 @@ declare module 'stream' { readonly writableLength: number; readonly writableObjectMode: boolean; readonly writableCorked: number; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `false`. + * + * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is + * emitted. + * @since v0.9.4 + */ allowHalfOpen: boolean; constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from(src: Stream | NodeBlob | ArrayBuffer | string | Iterable | AsyncIterable | AsyncGeneratorFunction | Promise | Object): Duplex; _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; _destroy(error: Error | null, callback: (error: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; @@ -269,91 +863,401 @@ declare module 'stream' { cork(): void; uncork(): void; } - type TransformCallback = (error?: Error | null, data?: any) => void; - interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; read?(this: Transform, size: number): void; write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?(this: Transform, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; final?(this: Transform, callback: (error?: Error | null) => void): void; destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; flush?(this: Transform, callback: TransformCallback): void; } - + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ class Transform extends Duplex { constructor(opts?: TransformOptions); _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; _flush(callback: TransformCallback): void; } - - class PassThrough extends Transform { } - - interface FinishedOptions { + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + interface FinishedOptions extends Abortable { error?: boolean | undefined; readable?: boolean | undefined; writable?: boolean | undefined; } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; namespace finished { function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; } - - function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; - function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: T, - callback?: (err: NodeJS.ErrnoException | null) => void, - ): T; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: NodeJS.ReadWriteStream, - stream5: T, - callback?: (err: NodeJS.ErrnoException | null) => void, - ): T; + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends PipelineTransformSource + ? NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends PipelineDestinationPromiseFunction + ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, signal) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function * (signal) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline( streams: ReadonlyArray, - callback?: (err: NodeJS.ErrnoException | null) => void, + callback?: (err: NodeJS.ErrnoException | null) => void ): NodeJS.WritableStream; function pipeline( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array void)>, + ...streams: Array void)> ): NodeJS.WritableStream; namespace pipeline { - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; - function __promisify__( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: NodeJS.ReadWriteStream, - stream5: NodeJS.WritableStream, - ): Promise; - function __promisify__(streams: ReadonlyArray): Promise; + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__(streams: ReadonlyArray, options?: PipelineOptions): Promise; function __promisify__( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array, + ...streams: Array ): Promise; } - interface Pipe { close(): void; hasRef(): boolean; ref(): void; unref(): void; } - } + /** + * Returns whether the stream has encountered an error. + * @since v16.14.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + + /** + * Returns whether the stream is readable. + * @since v16.14.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } export = internal; } declare module 'node:stream' { diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/stream/consumers.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/stream/consumers.d.ts new file mode 100644 index 000000000..d00e234db --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/stream/consumers.d.ts @@ -0,0 +1,15 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +declare module 'stream/consumers' { + import { Readable } from 'node:stream'; + import { Blob as NodeBlob } from "node:buffer"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterator): Promise; +} +declare module 'node:stream/consumers' { + export * from 'stream/consumers'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/stream/promises.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/stream/promises.d.ts new file mode 100644 index 000000000..384c4f884 --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/stream/promises.d.ts @@ -0,0 +1,45 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream'; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + function pipeline, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module 'node:stream/promises' { + export * from 'stream/promises'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/stream/web.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/stream/web.d.ts new file mode 100644 index 000000000..3e26845cb --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/stream/web.d.ts @@ -0,0 +1,395 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: 'bytes'; + } + + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + const ReadableStream: { + prototype: ReadableStream; + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new (stream: ReadableStream): ReadableStreamDefaultReader; + }; + + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new (): ReadableByteStreamController; + }; + + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new (): ReadableStreamDefaultController; + }; + + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + + const TransformStream: { + prototype: TransformStream; + new ( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new (): TransformStreamDefaultController; + }; + + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + + const WritableStream: { + prototype: WritableStream; + new (underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new (stream: WritableStream): WritableStreamDefaultWriter; + }; + + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new (): WritableStreamDefaultController; + }; + + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + + interface QueuingStrategySize { + (chunk?: T): number; + } + + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new (init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new (init: QueuingStrategyInit): CountQueuingStrategy; + }; + + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: 'utf-8'; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + + const TextEncoderStream: { + prototype: TextEncoderStream; + new (): TextEncoderStream; + }; + + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + + type BufferSource = ArrayBufferView | ArrayBuffer; + + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + + const TextDecoderStream: { + prototype: TextDecoderStream; + new (label?: string, options?: TextDecoderOptions): TextDecoderStream; + }; +} +declare module 'node:stream/web' { + export * from 'stream/web'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/string_decoder.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/string_decoder.d.ts index ebcfa3005..2ab7c8d5b 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/string_decoder.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/string_decoder.d.ts @@ -1,10 +1,67 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `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('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * 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('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.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 A `Buffer`, or `TypedArray`, or `DataView` containing 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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ end(buffer?: Buffer): string; } } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/test.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/test.d.ts new file mode 100644 index 000000000..8189c30dd --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/test.d.ts @@ -0,0 +1,193 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v16.17.0/lib/test.js) + */ +declare module 'node:test' { + /** + * The `test()` function is the value imported from the test module. Each invocation of this + * function results in the creation of a test point in the TAP output. + * + * The {@link TestContext} object passed to the fn argument can be used to perform actions + * related to the current test. Examples include skipping the test, adding additional TAP + * diagnostic information, or creating subtests. + * + * `test()` returns a {@link Promise} that resolves once the test completes. The return value + * can usually be discarded for top level tests. However, the return value from subtests should + * be used to prevent the parent test from finishing first and cancelling the subtest as shown + * in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * @since v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + + /** + * @since v16.17.0 + * @param name The name of the suite, which is displayed when reporting suite results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite + * @param fn The function under suite. Default: A no-op function. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function describe(name?: string, fn?: SuiteFn): void; + function describe(options?: TestOptions, fn?: SuiteFn): void; + function describe(fn?: SuiteFn): void; + + /** + * @since v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + */ + function it(name?: string, options?: TestOptions, fn?: ItFn): void; + function it(name?: string, fn?: ItFn): void; + function it(options?: TestOptions, fn?: ItFn): void; + function it(fn?: ItFn): void; + + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => any; + + /** + * The type of a function under Suite. + * If the test uses callbacks, the callback function is passed as an argument + */ + type SuiteFn = (done: (result?: any) => void) => void; + + /** + * The type of a function under test. + * If the test uses callbacks, the callback function is passed as an argument + */ + type ItFn = (done: (result?: any) => void) => any; + + /** + * An instance of `TestContext` is passed to each test function in order to interact with the + * test runner. However, the `TestContext` constructor is not exposed as part of the API. + * @since v16.17.0 + */ + interface TestContext { + /** + * This function is used to write TAP diagnostics to the output. Any diagnostic information is + * included at the end of the test's results. This function does not return a value. + * @param message Message to be displayed as a TAP diagnostic. + * @since v16.17.0 + */ + diagnostic(message: string): void; + + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that have the `only` + * option set. Otherwise, all tests are run. If Node.js was not started with the `--test-only` + * command-line option, this function is a no-op. + * @param shouldRunOnlyTests Whether or not to run `only` tests. + * @since v16.17.0 + */ + runOnly(shouldRunOnlyTests: boolean): void; + + /** + * This function causes the test's output to indicate the test as skipped. If `message` is + * provided, it is included in the TAP output. Calling `skip()` does not terminate execution of + * the test function. This function does not return a value. + * @param message Optional skip message to be displayed in TAP output. + * @since v16.17.0 + */ + skip(message?: string): void; + + /** + * This function adds a `TODO` directive to the test's output. If `message` is provided, it is + * included in the TAP output. Calling `todo()` does not terminate execution of the test + * function. This function does not return a value. + * @param message Optional `TODO` message to be displayed in TAP output. + * @since v16.17.0 + */ + todo(message?: string): void; + + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + } + + interface TestOptions { + /** + * The number of tests that can be run at the same time. If unspecified, subtests inherit this + * value from their parent. + * @default 1 + */ + concurrency?: number; + + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean; + + /** + * Allows aborting an in-progress test. + * @since v16.17.0 + */ + signal?: AbortSignal; + + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string; + + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v16.17.0 + */ + timeout?: number; + + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string; + } + + export { test as default, test, describe, it }; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/timers.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/timers.d.ts index 2afe53c8d..eae3fcd68 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/timers.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/timers.d.ts @@ -1,21 +1,96 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * 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('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/v16.9.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; - function __promisify__(ms: number, value: T): Promise; + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } 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; - function __promisify__(value: T): Promise; + 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; + } + interface Immediate extends RefCounted { + /** + * 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 + } + interface Timeout extends Timer { + /** + * 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; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + 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'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/timers/promises.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/timers/promises.d.ts new file mode 100644 index 000000000..74554e527 --- /dev/null +++ b/packages/node_modules/@node-red/editor-client/src/types/node/timers/promises.d.ts @@ -0,0 +1,96 @@ + +/* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ + +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module 'timers/promises' { + import { TimerOptions } from 'node:timers'; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + + const scheduler: Scheduler; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/tls.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/tls.d.ts index 508055923..989be9f23 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/tls.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/tls.d.ts @@ -1,13 +1,21 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `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('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/tls.js) + */ declare module 'tls' { - import * as net from 'net'; - import * as stream from 'stream'; - + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; const CLIENT_RENEG_LIMIT: number; const CLIENT_RENEG_WINDOW: number; - interface Certificate { /** * Country code. @@ -34,7 +42,6 @@ declare module 'tls' { */ CN: string; } - interface PeerCertificate { subject: Certificate; issuer: Certificate; @@ -50,11 +57,9 @@ declare module 'tls' { serialNumber: string; raw: Buffer; } - interface DetailedPeerCertificate extends PeerCertificate { issuerCertificate: DetailedPeerCertificate; } - interface CipherNameAndProtocol { /** * The cipher name. @@ -64,13 +69,11 @@ declare module 'tls' { * SSL/TLS protocol version. */ version: string; - /** * IETF name for the cipher suite. */ standardName: string; } - interface EphemeralKeyInfo { /** * The supported types are 'DH' and 'ECDH'. @@ -85,7 +88,6 @@ declare module 'tls' { */ size: number; } - interface KeyObject { /** * Private keys in PEM format. @@ -96,7 +98,6 @@ declare module 'tls' { */ passphrase?: string | undefined; } - interface PxfObject { /** * PFX or PKCS12 encoded private key and certificate chain. @@ -107,7 +108,6 @@ declare module 'tls' { */ passphrase?: string | undefined; } - interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { /** * If true the TLS socket will be instantiated in server-mode. @@ -118,7 +118,6 @@ declare module 'tls' { * An optional net.Server instance. */ server?: net.Server | undefined; - /** * An optional Buffer instance containing a TLS session. */ @@ -130,227 +129,307 @@ declare module 'tls' { */ 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 { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ 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. + * Returns `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. * 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 | 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: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * 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. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | 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 | undefined, requestCert?: boolean | undefined }, 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; - /** * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. * - * 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, + * 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. + * @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: + * + * + * ``` + * + * 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; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; - addListener(event: "session", listener: (session: Buffer) => void): this; - addListener(event: "keylog", listener: (line: Buffer) => void): this; - + addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + addListener(event: 'secureConnect', listener: () => void): this; + addListener(event: 'session', listener: (session: Buffer) => void): this; + addListener(event: 'keylog', listener: (line: Buffer) => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; - emit(event: "session", session: Buffer): boolean; - emit(event: "keylog", line: Buffer): boolean; - + emit(event: 'OCSPResponse', response: Buffer): boolean; + emit(event: 'secureConnect'): boolean; + emit(event: 'session', session: Buffer): boolean; + emit(event: 'keylog', line: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; - on(event: "session", listener: (session: Buffer) => void): this; - on(event: "keylog", listener: (line: Buffer) => void): this; - + on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + on(event: 'secureConnect', listener: () => void): this; + on(event: 'session', listener: (session: Buffer) => void): this; + on(event: 'keylog', listener: (line: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; - once(event: "session", listener: (session: Buffer) => void): this; - once(event: "keylog", listener: (line: Buffer) => void): this; - + once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + once(event: 'secureConnect', listener: () => void): this; + once(event: 'session', listener: (session: Buffer) => void): this; + once(event: 'keylog', listener: (line: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; - prependListener(event: "session", listener: (session: Buffer) => void): this; - prependListener(event: "keylog", listener: (line: Buffer) => void): this; - + prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependListener(event: 'secureConnect', listener: () => void): this; + prependListener(event: 'session', listener: (session: Buffer) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - prependOnceListener(event: "session", listener: (session: Buffer) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependOnceListener(event: 'secureConnect', listener: () => void): this; + prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; } - interface CommonConnectionOptions { /** * An optional TLS context object from tls.createSecureContext() */ secureContext?: SecureContext | undefined; - /** * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. @@ -377,7 +456,7 @@ declare module 'tls' { * SecureContext.) If SNICallback wasn't provided the default callback * with high-level API will be used (see below). */ - SNICallback?: ((servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void) | undefined; + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; /** * If true the server will reject any connection which is not * authorized with the list of supplied CAs. This option only has an @@ -386,7 +465,6 @@ declare module 'tls' { */ rejectUnauthorized?: boolean | undefined; } - interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { /** * Abort the connection if the SSL/TLS handshake does not finish in the @@ -405,7 +483,6 @@ declare module 'tls' { * 48-bytes of cryptographically strong pseudo-random data. */ ticketKeys?: Buffer | undefined; - /** * * @param socket @@ -425,7 +502,6 @@ declare module 'tls' { * requires explicitly specifying a cipher suite with the `ciphers` option. * More information can be found in the RFC 4279. */ - pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; /** * hint to send to a client to help @@ -435,17 +511,15 @@ declare module 'tls' { */ pskIdentityHint?: string | undefined; } - interface PSKCallbackNegotation { psk: DataView | NodeJS.TypedArray; identity: string; } - interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { 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 + socket?: net.Socket | 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; @@ -471,35 +545,50 @@ declare module 'tls' { */ pskCallback?(hint: string | null): PSKCallbackNegotation | null; } - + /** + * 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). */ - 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; - /** * events.EventEmitter * 1. tlsClientError @@ -510,61 +599,56 @@ declare module 'tls' { * 6. keylog */ addListener(event: string, listener: (...args: any[]) => void): this; - 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: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => 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: "secureConnection", tlsSocket: TLSSocket): boolean; - emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; - + emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): 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: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => 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: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => 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: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => 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: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => 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 { encrypted: TLSSocket; cleartext: TLSSocket; } - type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; - interface SecureContextOptions { /** * Optionally override the trusted CA certificates. Default is to trust @@ -723,31 +807,183 @@ declare module 'tls' { */ 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 can be overwritten by providing alternative function as part of + * the `options.checkServerIdentity` option 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`). + * @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(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 `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('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 checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; 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('tls'); + * const fs = require('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, 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(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 {@link createServer} and `server.addContext()`, but has no public methods. + * + * 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). + * @since v0.11.13 */ - function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; 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}. + * + * 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[]; - /** * The default curve name to use for ECDH key agreement in a tls server. * The default value is 'auto'. See tls.createSecureContext() for further @@ -774,7 +1010,6 @@ declare module 'tls' { * are provided, the lowest minimum is used. */ let DEFAULT_MIN_VERSION: SecureVersion; - /** * An immutable array of strings representing the root certificates (in PEM * format) used for verifying peer certificates. This is the default value diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/trace_events.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/trace_events.d.ts index bb037dec0..3bf9d03d4 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/trace_events.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/trace_events.d.ts @@ -1,6 +1,83 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `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 `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.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync 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 `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * 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 `trace_events` module: + * + * ```js + * const trace_events = require('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 + * ``` + * + * 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/v16.9.0/lib/trace_events.js) + */ declare module 'trace_events' { /** * The `Tracing` object is used to enable or disable tracing for sets of @@ -18,7 +95,6 @@ declare module 'trace_events' { * `Tracing` object. */ readonly categories: string; - /** * Disables this `Tracing` object. * @@ -27,19 +103,16 @@ declare module 'trace_events' { * will be disabled. */ disable(): void; - /** * Enables this `Tracing` object for the set of categories covered by * the `Tracing` object. */ enable(): void; - /** * `true` only if the `Tracing` object has been enabled. */ readonly enabled: boolean; } - interface CreateTracingOptions { /** * An array of trace category names. Values included in the array are @@ -48,17 +121,41 @@ declare module 'trace_events' { */ categories: string[]; } - /** - * 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('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('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; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/tty.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/tty.d.ts index 8292139ad..05677f575 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/tty.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/tty.d.ts @@ -1,14 +1,71 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `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('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/v16.9.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. Defaults to `false`. + * @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,53 +74,131 @@ declare module 'tty' { * 1 - to the right from cursor */ 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 { constructor(fd: number); addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "resize", listener: () => void): this; - + addListener(event: 'resize', listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "resize"): boolean; - + emit(event: 'resize'): boolean; on(event: string, listener: (...args: any[]) => void): this; - on(event: "resize", listener: () => void): this; - + on(event: 'resize', listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; - once(event: "resize", listener: () => void): this; - + once(event: 'resize', listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "resize", listener: () => void): this; - + prependListener(event: 'resize', listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "resize", listener: () => 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`. */ cursorTo(x: number, y?: number, callback?: () => void): boolean; cursorTo(x: 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?: 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 */ - getColorDepth(env?: {}): number; - hasColors(depth?: number): boolean; - hasColors(env?: {}): boolean; - hasColors(depth: number, env?: {}): boolean; 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; } } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/url.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/url.d.ts index 80ab2595f..120060fb9 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/url.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/url.d.ts @@ -1,9 +1,19 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/url.js) + */ declare module 'url' { - import { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring'; - + import { Blob } from 'node:buffer'; + import { ClientRequestArgs } from 'node:http'; + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; // Input to `url.format` interface UrlObject { auth?: string | null | undefined; @@ -18,7 +28,6 @@ declare module 'url' { port?: string | number | null | undefined; query?: string | null | ParsedUrlQueryInput | undefined; } - // Output of `url.parse` interface Url { auth: string | null; @@ -34,85 +43,782 @@ declare module 'url' { port: string | null; query: string | null | ParsedUrlQuery; } - 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. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * + * Deprecation of this API has been shelved for now primarily due to the the + * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). + * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. + * + * @since v0.1.25 + * @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 object has both a `toString()` method and `href` property that return string serializations of the URL. + * These are not, however, customizable in any way. The `url.format(URL[, options])` method allows for basic + * customization of the output. + * Returns a customizable serialization of a URL `String` representation of a `WHATWG URL` object. + * + * ```js + * import url from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(myURL.href); + * // Prints https://a:b@xn--g6w251d/?abc#foo + * + * console.log(myURL.toString()); + * // Prints https://a:b@xn--g6w251d/?abc#foo + * + * console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); + * // Prints 'https://測試/?abc' + * ``` + * @since v7.6.0 + * @param urlObject A `WHATWG URL` object + * @param options + */ + 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 + * @deprecated 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 HREF. + * + * ```js + * const url = require('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' + * ``` + * + * You can 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 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The Base URL being resolved against. + * @param to The HREF URL being resolved. + */ 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}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from '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}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from '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 '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 '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 '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 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; interface URLFormatOptions { 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('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: Blob): string; + /** + * Removes the stored `Blob` identified by the given ID. + * @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; 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:82'; + * 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: + * + * + * + * 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 | Record> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + /** + * Append a new name-value pair to the query string. + */ append(name: string, value: string): void; + /** + * Remove all name-value pairs whose name is `name`. + */ delete(name: 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: URLSearchParams) => void, thisArg?: any): 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(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[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ has(name: 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; + /** + * 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; + /** + * 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; [Symbol.iterator](): IterableIterator<[string, string]>; } diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/util.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/util.d.ts index 54522c6b0..627321b74 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/util.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/util.d.ts @@ -1,219 +1,1597 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/util.js) + */ declare module 'util' { - interface InspectOptions extends NodeJS.InspectOptions { } - type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; - type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; - interface InspectOptionsStylized extends InspectOptions { + import * as types from 'node:util/types'; + export 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 | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * 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 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * 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 | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { stylize(text: string, styleType: Style): string; } - function format(format?: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; - function getSystemErrorName(err: number): string; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0 + */ + export function toUSVString(string: string): string; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export namespace inspect { let colors: NodeJS.Dict<[number, number]>; let styles: { - [K in Style]: string + [K in Style]: string; }; let defaultOptions: InspectOptions; /** * Allows changing inspect settings from the repl. */ let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ const custom: unique symbol; } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - type DebugLoggerFunction = (msg: string, ...param: any[]) => void; - interface DebugLogger extends DebugLoggerFunction { + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { enabled: boolean; } - function debuglog(key: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; - const debug: typeof debuglog; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string, code?: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && err.hasOwnProperty('reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( + export function callbackify( fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - interface CustomPromisifyLegacy extends Function { + export interface CustomPromisifyLegacy extends Function { __promisify__: TCustom; } - - interface CustomPromisifySymbol extends Function { + export interface CustomPromisifySymbol extends Function { [promisify.custom]: TCustom; } - - type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): - (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): - (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - namespace promisify { + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ const custom: unique symbol; } - - namespace types { - function isAnyArrayBuffer(object: any): object is ArrayBufferLike; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is NodeJS.ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBigInt64Array(value: any): value is BigInt64Array; - function isBigUint64Array(value: any): value is BigUint64Array; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is String | Number | BigInt | Boolean | Symbol; - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): object is GeneratorFunction; - function isGeneratorObject(object: any): object is Generator; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap( - object: T | {}, - ): object is T extends ReadonlyMap - ? unknown extends T - ? never - : ReadonlyMap - : Map; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): object is Promise; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet( - object: T | {}, - ): object is T extends ReadonlySet - ? unknown extends T - ? never - : ReadonlySet - : Set; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): object is SharedArrayBuffer; - function isStringObject(object: any): object is String; - function isSymbolObject(object: any): object is Symbol; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): object is WeakMap; - function isWeakSet(object: any): object is WeakSet; - } - - class TextDecoder { + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder('shift_jis'); + * let string = ''; + * let buffer; + * while (buffer = getNextChunkSomehow()) { + * string += decoder.decode(buffer, { stream: true }); + * } + * string += decoder.decode(); // end-of-stream + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ readonly ignoreBOM: boolean; constructor( - encoding?: string, - options?: { fatal?: boolean | undefined; ignoreBOM?: boolean | undefined } + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + } ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ decode( - input?: NodeJS.ArrayBufferView | ArrayBuffer | null, - options?: { stream?: boolean | undefined } + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + } ): string; } - - interface EncodeIntoResult { + export interface EncodeIntoResult { /** * The read Unicode code units of input. */ - read: number; /** * The written UTF-8 bytes of output. */ written: number; } - - class TextEncoder { + export { types }; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ encode(input?: string): Uint8Array; - encodeInto(input: string, output: Uint8Array): EncodeIntoResult; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; } } +declare module 'util/types' { + export * from 'util/types'; +} +declare module 'util/types' { + import { KeyObject, webcrypto } from 'node:crypto'; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} declare module 'node:util' { export * from 'util'; } +declare module 'node:util/types' { + export * from 'util/types'; +} diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/v8.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/v8.d.ts index 50218efc9..08edd2e65 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/v8.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/v8.d.ts @@ -1,9 +1,16 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `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('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/v8.js) + */ declare module 'v8' { - import { Readable } from 'stream'; - + import { Readable } from 'node:stream'; interface HeapSpaceInfo { space_name: string; space_size: number; @@ -11,10 +18,8 @@ declare module 'v8' { space_available_size: number; physical_space_size: number; } - // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ type DoesZapCodeSpaceFlag = 0 | 1; - interface HeapInfo { total_heap_size: number; total_heap_size_executable: number; @@ -28,165 +33,348 @@ declare module 'v8' { number_of_native_contexts: number; number_of_detached_contexts: number; } - interface HeapCodeStatistics { code_and_metadata_size: number; bytecode_and_metadata_size: number; external_script_source_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. + * + * ```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 + * } + * ``` + * @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('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ function setFlagsFromString(flags: string): void; /** * Generates a snapshot of the current V8 heap and returns a Readable * 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. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream 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. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('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; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 */ - function writeHeapSnapshot(fileName?: string): string; - function getHeapCodeStatistics(): HeapCodeStatistics; - + /** + * @since v8.0.0 + */ class Serializer { /** * Writes out a header, which includes the serialization format version. */ 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 {} + /** + * @since v8.0.0 */ - class DefaultSerializer extends Serializer { - } - class Deserializer { 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; - /** * 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. + * @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, 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, v12.22.0 + */ + function stopCoverage(): void; } declare module 'node:v8' { export * from 'v8'; diff --git a/packages/node_modules/@node-red/editor-client/src/types/node/vm.d.ts b/packages/node_modules/@node-red/editor-client/src/types/node/vm.d.ts index c5e57d83e..06a741b2d 100644 --- a/packages/node_modules/@node-red/editor-client/src/types/node/vm.d.ts +++ b/packages/node_modules/@node-red/editor-client/src/types/node/vm.d.ts @@ -1,8 +1,44 @@ /* NOTE: Do not edit directly! This file is generated using `npm run update-types` in https://github.com/Steve-Mcl/monaco-editor-esm-i18n */ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. **The `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('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/v16.9.0/lib/vm.js) + */ declare module 'vm' { - interface Context extends NodeJS.Dict { } + interface Context extends NodeJS.Dict {} interface BaseOptions { /** * Specifies the filename used in stack traces produced by this script. @@ -64,13 +100,11 @@ declare module 'vm' { * The sandbox/context in which the said function should be compiled in. */ parsingContext?: Context | undefined; - /** * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling */ contextExtensions?: Object[] | undefined; } - interface CreateContextOptions { /** * Human-readable name of the newly created context. @@ -85,27 +119,27 @@ declare module 'vm' { * @default '' */ 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; + 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'; - interface MeasureMemoryOptions { /** * @default 'summary' @@ -113,42 +147,360 @@ declare module 'vm' { mode?: MeasureMemoryMode | undefined; context?: Context | undefined; } - interface MemoryMeasurement { total: { jsMemoryEstimate: number; jsMemoryRange: [number, number]; }; } - + /** + * 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; + /** + * 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('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('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?: RunningScriptOptions): 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('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. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; } - function createContext(sandbox?: Context, options?: CreateContextOptions): Context; - 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, options?: CompileFunctionOptions): Function; - /** - * Measure the memory known to V8 and used by the current execution context or a specified context. + * 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('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 `