diff --git a/packages/bun-types/.eslintrc.cjs b/packages/bun-types/.eslintrc.cjs index 6fd18dcc96..d4f6944861 100644 --- a/packages/bun-types/.eslintrc.cjs +++ b/packages/bun-types/.eslintrc.cjs @@ -11,6 +11,7 @@ module.exports = { "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier", + "plugin:@definitelytyped/all", ], rules: { "no-var": "off", // global variables @@ -20,5 +21,16 @@ module.exports = { "@typescript-eslint/no-empty-function": "off", "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/no-misused-new": "off", + "@typescript-eslint/triple-slash-reference": "off", + "@typescript-eslint/no-empty-interface": "off", + "@definitelytyped/no-single-declare-module": "off", + "@definitelytyped/no-self-import": "off", + "@definitelytyped/no-unnecessary-generics": "off", + "@typescript-eslint/no-duplicate-enum-values": "off", + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/no-invalid-void-type": "off", + "@definitelytyped/no-single-element-tuple-type": "off", + "@typescript-eslint/no-non-null-asserted-optional-chain": "off", + "@typescript-eslint/unbound-method": "off", }, }; diff --git a/packages/bun-types/README.md b/packages/bun-types/README.md index c11c1371d1..c51b1b22fa 100644 --- a/packages/bun-types/README.md +++ b/packages/bun-types/README.md @@ -8,31 +8,19 @@ These are the type definitions for Bun's JavaScript runtime APIs. # Installation -Install the `bun-types` npm package: +Install the `@types/bun` npm package: ```bash -# yarn/npm/pnpm work too, "bun-types" is an ordinary npm package -bun add -d bun-types +# yarn/npm/pnpm work too +# @types/bun is an ordinary npm package +bun add -D @types/bun ``` -# Usage - -Add this to your `tsconfig.json` or `jsconfig.json`: - -```jsonc-diff - { - "compilerOptions": { -+ "types": ["bun-types"] - // other options... - } - - // other options... - } -``` +That's it! VS Code and TypeScript automatically load `@types/*` packages into your project, so the `Bun` global and all `bun:*` modules should be available immediately. # Contributing -`bun-types` is generated via [./scripts/bundle.ts](./scripts/bundle.ts). +The `@types/bun` package is a shim that loads `bun-types`. The `bun-types` package lives in the Bun repo under `packages/bun-types`. It is generated via [./scripts/bundle.ts](./scripts/bundle.ts). To add a new file, add it under `packages/bun-types`. Then add a [triple-slash directive](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) pointing to it inside [./index.d.ts](./index.d.ts). diff --git a/packages/bun-types/assert.d.ts b/packages/bun-types/assert.d.ts deleted file mode 100644 index 658e7df5b6..0000000000 --- a/packages/bun-types/assert.d.ts +++ /dev/null @@ -1,972 +0,0 @@ -/** - * The `assert` module provides a set of assertion functions for verifying - * invariants. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/assert.js) - */ -declare module "assert" { - /** - * An alias of {@link ok}. - * @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: 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?: unknown | undefined; - /** The `expected` property on the error instance. */ - expected?: unknown | undefined; - /** The `operator` property on the error instance. */ - operator?: string | undefined; - /** If provided, the generated stack trace omits frames before this function. */ - // tslint:disable-next-line:ban-types - stackStartFn?: Function | undefined; - }); - } - /** - * This feature is currently experimental and behavior might still change. - * @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); - * ``` - * @param [fn='A no-op function'] - * @param [exact=1] - * @return that wraps `fn`. - */ - calls(exact?: number): () => void; - calls any>( - fn?: Func, - exact?: number, - ): Func; - /** - * 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 - * // } - * // ] - * ``` - * @return of objects containing information about the wrapper functions returned by `calls`. - */ - report(): CallTrackerReportInformation[]; - /** - * 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(); - * ``` - */ - verify(): void; - } - interface CallTrackerReportInformation { - message: string; - /** The actual number of times the function was called. */ - actual: number; - /** The number of times the function was expected to be called. */ - expected: number; - /** The name of the function that is wrapped. */ - operator: string; - /** A stack trace of the function. */ - stack: object; - } - 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. - * @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: unknown, - expected: unknown, - message?: string | Error, - operator?: string, - // tslint:disable-next-line:ban-types - stackStartFn?: Function, - ): never; - /** - * 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) - * ``` - */ - function ok(value: unknown, message?: string | Error): asserts value; - /** - * **Strict assertion mode** - * - * An alias of {@link strictEqual}. - * - * **Legacy assertion mode** - * - * > Stability: 3 - Legacy: Use {@link strictEqual} instead. - * - * Tests shallow, coercive equality between the `actual` and `expected` parameters - * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled - * and treated as being identical if both sides are `NaN`. - * - * ```js - * import assert from '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`. - */ - function equal( - actual: unknown, - expected: unknown, - message?: string | Error, - ): void; - /** - * **Strict assertion mode** - * - * An alias of {@link notStrictEqual}. - * - * **Legacy assertion mode** - * - * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. - * - * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is - * specially handled and treated as being identical if both sides are `NaN`. - * - * ```js - * import assert from '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`. - */ - 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. - */ - 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`. - */ - function notDeepEqual( - actual: unknown, - expected: unknown, - message?: string | Error, - ): void; - /** - * Tests strict equality between the `actual` and `expected` parameters as - * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). - * - * ```js - * import assert from '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`. - */ - 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 [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). - * - * ```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`. - */ - 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. - */ - 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`. - */ - 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. - */ - 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 - * ``` - */ - 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 - * ``` - */ - 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. - */ - 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(() => { - * // ... - * }); - * ``` - */ - 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`. - */ - 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`. - */ - // FIXME: assert.doesNotMatch is typed, but not in the browserify polyfill? - 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: unknown, message?: string | Error): asserts value; - equal: typeof strictEqual; - notEqual: typeof notStrictEqual; - deepEqual: typeof deepStrictEqual; - notDeepEqual: typeof notDeepStrictEqual; - // Mapped types and assertion functions are incompatible? - // TS2775: Assertions require every name in the call target - // to be declared with an explicit type annotation. - ok: typeof ok; - strictEqual: typeof strictEqual; - deepStrictEqual: typeof deepStrictEqual; - ifError: typeof ifError; - strict: typeof strict; - }; - } - export = assert; -} -declare module "node:assert" { - import assert = require("assert"); - export = assert; -} diff --git a/packages/bun-types/async_hooks.d.ts b/packages/bun-types/async_hooks.d.ts deleted file mode 100644 index 43de681caf..0000000000 --- a/packages/bun-types/async_hooks.d.ts +++ /dev/null @@ -1,554 +0,0 @@ -/** - * We strongly discourage the use of the `async_hooks` API. - * Other APIs that can cover most of its use cases include: - * - * * `AsyncLocalStorage` tracks async context - * * `process.getActiveResourcesInfo()` tracks active resources - * - * The `node:async_hooks` module provides an API to track asynchronous resources. - * It can be accessed using: - * - * ```js - * import async_hooks from 'node:async_hooks'; - * ``` - * @experimental - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) - */ -declare module "async_hooks" { - /** - * ```js - * import { executionAsyncId } from 'node:async_hooks'; - * import fs from 'node:fs'; - * - * 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 v0.7.0 - * @return The `asyncId` of the current execution context. Useful to track when something calls. - */ - function executionAsyncId(): number; - /** - * 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. - * - * 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 'node:fs'; - * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; - * - * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} - * open(new URL(import.meta.url), 'r', (err, fd) => { - * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap - * }); - * ``` - * - * This can be used to implement continuation local storage without the - * use of a tracking `Map` to store the metadata: - * - * ```js - * import { createServer } from 'node:http'; - * import { - * executionAsyncId, - * executionAsyncResource, - * createHook, - * } from 'async_hooks'; - * const sym = Symbol('state'); // Private symbol to avoid pollution - * - * createHook({ - * init(asyncId, type, triggerAsyncId, resource) { - * const cr = executionAsyncResource(); - * if (cr) { - * resource[sym] = cr[sym]; - * } - * }, - * }).enable(); - * - * const server = createServer((req, res) => { - * executionAsyncResource()[sym] = { state: req.url }; - * setTimeout(function() { - * res.end(JSON.stringify(executionAsyncResource()[sym])); - * }, 100); - * }).listen(3000); - * ``` - * @since v0.7.0 - * @return The resource representing the current execution. Useful to store data within the resource. - */ - function executionAsyncResource(): object; - /** - * ```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. - * @param asyncId a unique ID for the async resource - * @param type the type of the async resource - * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created - * @param resource reference to the resource representing the async operation, needs to be released during destroy - */ - 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. - * - * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the - * respective asynchronous event during a resource's lifetime. - * - * All callbacks are optional. For example, if only resource cleanup needs to - * be tracked, then only the `destroy` callback needs to be passed. The - * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. - * - * ```js - * import { createHook } from 'node:async_hooks'; - * - * const asyncHook = createHook({ - * init(asyncId, type, triggerAsyncId, resource) { }, - * destroy(asyncId) { }, - * }); - * ``` - * - * The callbacks will be inherited via the prototype chain: - * - * ```js - * class MyAsyncCallbacks { - * init(asyncId, type, triggerAsyncId, resource) { } - * destroy(asyncId) {} - * } - * - * class MyAddedCallbacks extends MyAsyncCallbacks { - * before(asyncId) { } - * after(asyncId) { } - * } - * - * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); - * ``` - * - * Because promises are asynchronous resources whose lifecycle is tracked - * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. - * @since v0.7.0 - * @param callbacks The `Hook Callbacks` to register - * @return Instance used for disabling and enabling hooks - */ - 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 class `AsyncResource` is designed to be extended by the embedder's async - * resources. Using this, users can easily trigger the lifetime events of their - * own resources. - * - * The `init` hook will trigger when an `AsyncResource` is instantiated. - * - * The following is an overview of the `AsyncResource` API. - * - * ```js - * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; - * - * // AsyncResource() is meant to be extended. Instantiating a - * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * // async_hook.executionAsyncId() is used. - * const asyncResource = new AsyncResource( - * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, - * ); - * - * // Run a function in the execution context of the resource. This will - * // * establish the context of the resource - * // * trigger the AsyncHooks before callbacks - * // * call the provided function `fn` with the supplied arguments - * // * trigger the AsyncHooks after callbacks - * // * restore the original execution context - * asyncResource.runInAsyncScope(fn, thisArg, ...args); - * - * // Call AsyncHooks destroy callbacks. - * asyncResource.emitDestroy(); - * - * // Return the unique ID assigned to the AsyncResource instance. - * asyncResource.asyncId(); - * - * // Return the trigger ID for the AsyncResource instance. - * asyncResource.triggerAsyncId(); - * ``` - */ - class AsyncResource { - /** - * AsyncResource() is meant to be extended. Instantiating a - * new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * async_hook.executionAsyncId() is used. - * @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 v9.3.0) - */ - constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); - /** - * Binds the given function to the current execution context. - * @since v0.7.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, ThisArg>( - fn: Func, - type?: string, - thisArg?: ThisArg, - ): Func; - /** - * Binds the given function to execute to this `AsyncResource`'s scope. - * @since v0.7.0 - * @param fn The function to bind to the current `AsyncResource`. - */ - bind any>(fn: Func): Func; - /** - * Call the provided function with the provided arguments in the execution context - * of the async resource. This will establish the context, trigger the AsyncHooks - * before callbacks, call the function, trigger the AsyncHooks after callbacks, and - * then restore the original execution context. - * @since v0.7.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 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 `asyncId` assigned to the resource. - */ - asyncId(): number; - /** - * - * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. - */ - triggerAsyncId(): number; - } - /** - * This class creates stores that stay coherent through asynchronous operations. - * - * While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory - * safe implementation that involves significant optimizations that are non-obvious - * to implement. - * - * The following example uses `AsyncLocalStorage` to build a simple logger - * that assigns IDs to incoming HTTP requests and includes them in messages - * logged within each request. - * - * ```js - * import http from 'node:http'; - * import { AsyncLocalStorage } from 'node:async_hooks'; - * - * const asyncLocalStorage = new AsyncLocalStorage(); - * - * function logWithId(msg) { - * const id = asyncLocalStorage.getStore(); - * console.log(`${id !== undefined ? id : '-'}:`, msg); - * } - * - * let idSeq = 0; - * http.createServer((req, res) => { - * asyncLocalStorage.run(idSeq++, () => { - * logWithId('start'); - * // Imagine any chain of async operations here - * setImmediate(() => { - * logWithId('finish'); - * res.end(); - * }); - * }); - * }).listen(8080); - * - * http.get('http://localhost:8080'); - * http.get('http://localhost:8080'); - * // Prints: - * // 0: start - * // 1: start - * // 0: finish - * // 1: finish - * ``` - * - * Each instance of `AsyncLocalStorage` maintains an independent storage context. - * Multiple instances can safely exist simultaneously without risk of interfering - * with each other's data. - * @since v0.7.0 - */ - class AsyncLocalStorage { - /** - * Binds the given function to the current execution context. - * @since v0.7.0 - * @experimental - * @param fn The function to bind to the current execution context. - * @return A new function that calls `fn` within the captured execution context. - */ - static bind any>(fn: Func): Func; - /** - * Captures the current execution context and returns a function that accepts a - * function as an argument. Whenever the returned function is called, it - * calls the function passed to it within the captured context. - * - * ```js - * const asyncLocalStorage = new AsyncLocalStorage(); - * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); - * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); - * console.log(result); // returns 123 - * ``` - * - * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple - * async context tracking purposes, for example: - * - * ```js - * class Foo { - * #runInAsyncScope = AsyncLocalStorage.snapshot(); - * - * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } - * } - * - * const foo = asyncLocalStorage.run(123, () => new Foo()); - * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 - * ``` - * @since v0.7.0 - * @experimental - * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. - */ - static snapshot(): ( - fn: (...args: TArgs) => R, - ...args: TArgs - ) => R; - /** - * Disables the instance of `AsyncLocalStorage`. All subsequent calls - * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. - * - * When calling `asyncLocalStorage.disable()`, all current contexts linked to the - * instance will be exited. - * - * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores - * provided by the `asyncLocalStorage`, as those objects are garbage collected - * along with the corresponding async resources. - * - * Use this method when the `asyncLocalStorage` is not in use anymore - * in the current process. - * @since v0.7.0 - * @experimental - */ - disable(): void; - /** - * Returns the current store. - * If called outside of an asynchronous context initialized by - * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it - * returns `undefined`. - * @since v0.7.0 - */ - getStore(): T | undefined; - /** - * Runs a function synchronously within a context and returns its - * return value. The store is not accessible outside of the callback function. - * The store is accessible to any asynchronous operations created within the - * callback. - * - * The optional `args` are passed to the callback function. - * - * If the callback function throws an error, the error is thrown by `run()` too. - * The stacktrace is not impacted by this call and the context is exited. - * - * Example: - * - * ```js - * const store = { id: 2 }; - * try { - * asyncLocalStorage.run(store, () => { - * asyncLocalStorage.getStore(); // Returns the store object - * setTimeout(() => { - * asyncLocalStorage.getStore(); // Returns the store object - * }, 200); - * throw new Error(); - * }); - * } catch (e) { - * asyncLocalStorage.getStore(); // Returns undefined - * // The error will be caught here - * } - * ``` - * @since v0.7.0 - */ - run( - store: T, - callback: (...args: TArgs) => R, - ...args: TArgs - ): R; - /** - * 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`. - * - * The optional `args` are passed to the callback function. - * - * 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 v0.7.0 - * @experimental - */ - exit( - callback: (...args: TArgs) => R, - ...args: TArgs - ): R; - /** - * 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 v0.7.0 - * @experimental - */ - enterWith(store: T): void; - } -} - -declare module "node:async_hooks" { - export * from "async_hooks"; -} diff --git a/packages/bun-types/buffer.d.ts b/packages/bun-types/buffer.d.ts deleted file mode 100644 index 6b9cc78c13..0000000000 --- a/packages/bun-types/buffer.d.ts +++ /dev/null @@ -1,2115 +0,0 @@ -/** - * `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/v18.0.0/lib/buffer.js) - */ -declare module "buffer" { - import { ArrayBufferView } from "bun"; - export const INSPECT_MAX_BYTES: number; - export const kMaxLength: number; - export type TranscodeEncoding = - | "ascii" - | "utf8" - | "utf16le" - | "ucs2" - | "latin1" - | "binary"; - export const SlowBuffer: { - /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ - new (size: number): Buffer; - prototype: Buffer; - }; - export { Buffer }; - /** - * @experimental - */ - export interface BlobOptions { - /** - * @default 'utf8' - */ - encoding?: BufferEncoding | undefined; - /** - * The Blob content-type. The intent is for `type` to convey - * the MIME media type of the data, however no validation of the type format - * is performed. - */ - type?: string | undefined; - } - global { - // Buffer class - 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. - */ - 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 - * ``` - */ - 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 - * ``` - * @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. - * @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 | ArrayBufferView | ArrayBufferLike, - 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. - * @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].) - * ``` - * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. - */ - compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; - /** - * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. - * - * ```js - * import { Buffer } from '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. - * @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. - * @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. - * @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. - */ - 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 - * ``` - * @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é - * ``` - * @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: - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - */ - 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 - * ``` - * @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`. - * @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, - ): -1 | 0 | 1; - /** - * 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 - * ``` - * @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 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 - * - * // With buf.slice(), the original buffer is modified. - * const notReallyCopiedBuf = buf.slice(); - * notReallyCopiedBuf[0]++; - * console.log(notReallyCopiedBuf.toString()); - * // Prints: cuffer - * console.log(buf.toString()); - * // Also prints: cuffer (!) - * ``` - * @deprecated Use `subarray` instead. - * @param [start=0] Where the new `Buffer` will start. - * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). - */ - slice(start?: number, end?: number): Buffer; - /** - * Returns a new `Buffer` that references the same memory as the original, but - * offset and cropped by the `start` and `end` indices. - * - * Specifying `end` greater than `buf.length` will return the same result as - * that of `end` equal to `buf.length`. - * - * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). - * - * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. - * - * ```js - * import { Buffer } from '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).) - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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 - */ - 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. - * @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 - */ - 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: - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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 - */ - 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: - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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 - */ - 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: - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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: - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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 - * ``` - * @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 - */ - 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 - * ``` - * @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 - */ - 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. - * @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. - * @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 - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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 - */ - 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. - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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 - */ - 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 - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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. - * ``` - * - * Note: as of Bun v0.1.2, this is not implemented yet. - * @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. - * ``` - * @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 - */ - 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. - * ``` - * @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 - */ - 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 - * ``` - * @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 - */ - 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. - * ``` - * @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 - */ - 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 - * ``` - * @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 - */ - 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. - * ``` - * @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. - * ``` - * @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 - * ``` - * @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. - * ``` - * @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 - * ``` - * @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. - * ``` - * @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 - * ``` - * @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. - * ``` - * @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 - * ``` - * @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. - * ``` - * @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. - * ``` - * @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. - * ``` - * @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: - * ``` - * @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 - */ - 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: - * ``` - * @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 - */ - 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: - * ``` - * @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 - */ - 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: - * ``` - * @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 - */ - 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: - * ``` - * @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 - */ - 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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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: - * ``` - * @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. - * ``` - * @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.subarray`. - * * 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. - * @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. - * @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] - * ``` - */ - 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 - * ``` - * @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 - * ``` - */ - 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 - * ``` - */ - values(): IterableIterator; - } - var Buffer: BufferConstructor; - } - - /** - * This function returns `true` if `input` contains only valid UTF-8-encoded data, - * including the case in which `input` is empty. - * - * Throws if the `input` is a detached array buffer. - * @since Bun v0.6.13 - * @param input The input to validate. - */ - export function isUtf8( - input: TypedArray | ArrayBufferLike | DataView, - ): boolean; - - /** - * This function returns `true` if `input` contains only valid ASCII-encoded data, - * including the case in which `input` is empty. - * - * Throws if the `input` is a detached array buffer. - * @since Bun v0.6.13 - * @param input The input to validate. - */ - export function isAscii( - input: TypedArray | ArrayBufferLike | DataView, - ): boolean; -} -declare module "node:buffer" { - export * from "buffer"; -} diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 71c5d08e5c..ab65b97226 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -1,9 +1,4 @@ -interface VoidFunction { - (): void; -} - /** - * * Bun.js runtime APIs * * @example @@ -17,28 +12,14 @@ interface VoidFunction { * ``` * * This module aliases `globalThis.Bun`. - * */ declare module "bun" { - type ArrayBufferView = TypedArray | DataView; + type ArrayBufferView = Bun.ArrayBufferView; + type StringOrBuffer = Bun.StringOrBuffer; + type PathLike = Bun.PathLike; import { Encoding as CryptoEncoding } from "crypto"; - - export interface Env extends Dict, NodeJS.ProcessEnv { + interface Env { NODE_ENV?: string; - - /** - * The timezone used by Intl, Date, etc. - * - * To change the timezone, set `Bun.env.TZ` or `process.env.TZ` to the time zone you want to use. - * - * You can view the current timezone with `Intl.DateTimeFormat().resolvedOptions().timeZone` - * - * @example - * ```js - * Bun.env.TZ = "America/Los_Angeles"; - * console.log(Intl.DateTimeFormat().resolvedOptions().timeZone); // "America/Los_Angeles" - * ``` - */ TZ?: string; } @@ -48,14 +29,13 @@ declare module "bun" { * Defaults to `process.env` as it was when the current Bun process launched. * * Changes to `process.env` at runtime won't automatically be reflected in the default value. For that, you can pass `process.env` explicitly. - * */ - export const env: Env; + const env: NodeJS.ProcessEnv; /** * The raw arguments passed to the process, including flags passed to Bun. If you want to easily read flags passed to your script, consider using `process.argv` instead. */ - export const argv: string[]; - export const origin: string; + const argv: string[]; + const origin: string; /** * Find the path to an executable, similar to typing which in your terminal. Reads the `PATH` environment variable unless overridden with `options.PATH`. @@ -63,144 +43,12 @@ declare module "bun" { * @param {string} command The name of the executable or script * @param {string} options.PATH Overrides the PATH environment variable * @param {string} options.cwd Limits the search to a particular directory in which to searc - * */ - export function which( + function which( command: string, options?: { PATH?: string; cwd?: string }, ): string | null; - export interface GlobScanOptions { - /** - * The root directory to start matching from. Defaults to `process.cwd()` - */ - cwd?: string; - - /** - * Allow patterns to match entries that begin with a period (`.`). - * - * @default false - */ - dot?: boolean; - - /** - * Return the absolute path for entries. - * - * @default false - */ - absolute?: boolean; - - /** - * Indicates whether to traverse descendants of symbolic link directories. - * - * @default false - */ - followSymlinks?: boolean; - - /** - * Throw an error when symbolic link is broken - * - * @default false - */ - throwErrorOnBrokenSymlink?: boolean; - - /** - * Return only files. - * - * @default true - */ - onlyFiles?: boolean; - } - - /** - * Match files using [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)). - * - * The supported pattern syntax for is: - * - * - `?` - * Matches any single character. - * - `*` - * Matches zero or more characters, except for path separators ('/' or '\'). - * - `**` - * Matches zero or more characters, including path separators. - * Must match a complete path segment, i.e. followed by a path separator or - * at the end of the pattern. - * - `[ab]` - * Matches one of the characters contained in the brackets. - * Character ranges (e.g. "[a-z]") are also supported. - * Use "[!ab]" or "[^ab]" to match any character *except* those contained - * in the brackets. - * - `{a,b}` - * Match one of the patterns contained in the braces. - * Any of the wildcards listed above can be used in the sub patterns. - * Braces may be nested up to 10 levels deep. - * - `!` - * Negates the result when at the start of the pattern. - * Multiple "!" characters negate the pattern multiple times. - * - `\` - * Used to escape any of the special characters above. - * - * @example - * ```js - * const glob = new Glob("*.{ts,tsx}"); - * const scannedFiles = await Array.fromAsync(glob.scan({ cwd: './src' })) - * ``` - */ - export class Glob { - constructor(pattern: string); - - /** - * Scan for files that match this glob pattern. Returns an async iterator. - * - * @example - * ```js - * const glob = new Glob("*.{ts,tsx}"); - * const scannedFiles = await Array.fromAsync(glob.scan({ cwd: './src' })) - * ``` - * - * @example - * ```js - * const glob = new Glob("*.{ts,tsx}"); - * for await (const path of glob.scan()) { - * // do something - * } - * ``` - */ - scan( - optionsOrCwd?: string | GlobScanOptions, - ): AsyncIterableIterator; - - /** - * Scan for files that match this glob pattern. Returns an iterator. - * - * @example - * ```js - * const glob = new Glob("*.{ts,tsx}"); - * const scannedFiles = Array.from(glob.scan({ cwd: './src' })) - * ``` - * - * @example - * ```js - * const glob = new Glob("*.{ts,tsx}"); - * for (const path of glob.scan()) { - * // do something - * } - * ``` - */ - scanSync(optionsOrCwd?: string | GlobScanOptions): IterableIterator; - - /** - * Match the glob against a string - * - * @example - * ```js - * const glob = new Glob("*.{ts,tsx}"); - * expect(glob.match('foo.ts')).toBeTrue(); - * ``` - */ - match(str: string): boolean; - } - interface TOML { /** * Parse a TOML string into a JavaScript object. @@ -208,13 +56,12 @@ declare module "bun" { * @param {string} command The name of the executable or script * @param {string} options.PATH Overrides the PATH environment variable * @param {string} options.cwd Limits the search to a particular directory in which to searc - * */ parse(input: string): object; } - export const TOML: TOML; + const TOML: TOML; - export type Serve = + type Serve = | ServeOptions | TLSServeOptions | UnixServeOptions @@ -260,7 +107,8 @@ declare module "bun" { * }); * ``` */ - export function serve(options: Serve): Server; + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + function serve(options: Serve): Server; /** * Synchronously resolve a `moduleId` as though it were imported from `parent` @@ -268,7 +116,7 @@ declare module "bun" { * On failure, throws a `ResolveMessage` */ // tslint:disable-next-line:unified-signatures - export function resolveSync(moduleId: string, parent: string): string; + function resolveSync(moduleId: string, parent: string): string; /** * Resolve a `moduleId` as though it were imported from `parent` @@ -278,10 +126,9 @@ declare module "bun" { * For now, use the sync version. There is zero performance benefit to using this async version. It exists for future-proofing. */ // tslint:disable-next-line:unified-signatures - export function resolve(moduleId: string, parent: string): Promise; + function resolve(moduleId: string, parent: string): Promise; /** - * * Use the fastest syscalls available to copy from `input` into `destination`. * * If `destination` exists, it must be a regular file or symlink to a file. If `destination`'s directory does not exist, it will be created by default. @@ -291,10 +138,12 @@ declare module "bun" { * @returns A promise that resolves with the number of bytes written. */ // tslint:disable-next-line:unified-signatures - export function write( + function write( destination: BunFile | PathLike, - input: Blob | TypedArray | ArrayBufferLike | string | BlobPart[], + input: Blob | NodeJS.TypedArray | ArrayBufferLike | string | Bun.BlobPart[], options?: { + /** If writing to a PathLike, set the permissions of the file. */ + mode?: number; /** * If `true`, create the parent directory if it doesn't exist. By default, this is `true`. * @@ -307,7 +156,6 @@ declare module "bun" { ): Promise; /** - * * Persist a {@link Response} body to disk. * * @param destination The file to write to. If the file doesn't exist, @@ -317,7 +165,7 @@ declare module "bun" { * @param input - `Response` object * @returns A promise that resolves with the number of bytes written. */ - export function write( + function write( destination: BunFile, input: Response, options?: { @@ -333,7 +181,6 @@ declare module "bun" { ): Promise; /** - * * Persist a {@link Response} body to disk. * * @param destinationPath The file path to write to. If the file doesn't @@ -344,7 +191,7 @@ declare module "bun" { * @returns A promise that resolves with the number of bytes written. */ // tslint:disable-next-line:unified-signatures - export function write( + function write( destinationPath: PathLike, input: Response, options?: { @@ -360,7 +207,6 @@ declare module "bun" { ): Promise; /** - * * Use the fastest syscalls available to copy from `input` into `destination`. * * If `destination` exists, it must be a regular file or symlink to a file. @@ -379,7 +225,7 @@ declare module "bun" { * @returns A promise that resolves with the number of bytes written. */ // tslint:disable-next-line:unified-signatures - export function write( + function write( destination: BunFile, input: BunFile, options?: { @@ -395,7 +241,6 @@ declare module "bun" { ): Promise; /** - * * Use the fastest syscalls available to copy from `input` into `destination`. * * If `destination` exists, it must be a regular file or symlink to a file. @@ -414,7 +259,7 @@ declare module "bun" { * @returns A promise that resolves with the number of bytes written. */ // tslint:disable-next-line:unified-signatures - export function write( + function write( destinationPath: PathLike, input: BunFile, options?: { @@ -429,7 +274,7 @@ declare module "bun" { }, ): Promise; - export interface SystemError extends Error { + interface SystemError extends Error { errno?: number | undefined; code?: string | undefined; path?: string | undefined; @@ -467,7 +312,7 @@ declare module "bun" { * This function is faster because it uses uninitialized memory when copying. Since the entire * length of the buffer is known, it is safe to use uninitialized memory. */ - export function concatArrayBuffers( + function concatArrayBuffers( buffers: Array, ): ArrayBuffer; @@ -482,7 +327,7 @@ declare module "bun" { * @param stream The stream to consume. * @returns A promise that resolves with the concatenated chunks or the concatenated chunks as an `ArrayBuffer`. */ - export function readableStreamToArrayBuffer( + function readableStreamToArrayBuffer( stream: ReadableStream, ): Promise | ArrayBuffer; @@ -494,7 +339,7 @@ declare module "bun" { * @param stream The stream to consume. * @returns A promise that resolves with the concatenated chunks as a {@link Blob}. */ - export function readableStreamToBlob(stream: ReadableStream): Promise; + function readableStreamToBlob(stream: ReadableStream): Promise; /** * Consume all data from a {@link ReadableStream} until it closes or errors. @@ -502,7 +347,7 @@ declare module "bun" { * Reads the multi-part or URL-encoded form data into a {@link FormData} object * * @param stream The stream to consume. - * @params multipartBoundaryExcludingDashes Optional boundary to use for multipart form data. If none is provided, assumes it is a URLEncoded form. + * @param multipartBoundaryExcludingDashes Optional boundary to use for multipart form data. If none is provided, assumes it is a URLEncoded form. * @returns A promise that resolves with the data encoded into a {@link FormData} object. * * ## Multipart form data example @@ -523,9 +368,12 @@ declare module "bun" { * formData.get("hello"); // "123" * ``` */ - export function readableStreamToFormData( - stream: ReadableStream, - multipartBoundaryExcludingDashes?: string | TypedArray | ArrayBufferView, + function readableStreamToFormData( + stream: ReadableStream, + multipartBoundaryExcludingDashes?: + | string + | NodeJS.TypedArray + | ArrayBufferView, ): Promise; /** @@ -536,7 +384,7 @@ declare module "bun" { * @param stream The stream to consume. * @returns A promise that resolves with the concatenated chunks as a {@link String}. */ - export function readableStreamToText(stream: ReadableStream): Promise; + function readableStreamToText(stream: ReadableStream): Promise; /** * Consume all data from a {@link ReadableStream} until it closes or errors. @@ -546,16 +394,15 @@ declare module "bun" { * @param stream The stream to consume. * @returns A promise that resolves with the concatenated chunks as a {@link String}. */ - export function readableStreamToJSON(stream: ReadableStream): Promise; + function readableStreamToJSON(stream: ReadableStream): Promise; /** * Consume all data from a {@link ReadableStream} until it closes or errors. * * @param stream The stream to consume * @returns A promise that resolves with the chunks as an array - * */ - export function readableStreamToArray( + function readableStreamToArray( stream: ReadableStream, ): Promise | T[]; @@ -574,7 +421,7 @@ declare module "bun" { * * Non-string types will be converted to a string before escaping. */ - export function escapeHTML(input: string | object | number | boolean): string; + function escapeHTML(input: string | object | number | boolean): string; /** * Convert a filesystem path to a file:// URL. @@ -586,14 +433,14 @@ declare module "bun" { * ```js * const url = Bun.pathToFileURL("/foo/bar.txt"); * console.log(url.href); // "file:///foo/bar.txt" - *``` + * ``` * * Internally, this function uses WebKit's URL API to * convert the path to a file:// URL. */ - export function pathToFileURL(path: string): URL; + function pathToFileURL(path: string): URL; - export interface Peek { + interface Peek { (promise: T | Promise): Promise | T; status( promise: T | Promise, @@ -602,7 +449,7 @@ declare module "bun" { /** * Extract the value from the Promise in the same tick of the event loop */ - export const peek: Peek; + const peek: Peek; /** * Convert a {@link URL} to a filesystem path. @@ -615,12 +462,12 @@ declare module "bun" { * console.log(path); // "/foo/bar.txt" * ``` */ - export function fileURLToPath(url: URL): string; + function fileURLToPath(url: URL): string; /** * Fast incremental writer that becomes an `ArrayBuffer` on end(). */ - export class ArrayBufferSink { + class ArrayBufferSink { constructor(); start(options?: { @@ -653,7 +500,7 @@ declare module "bun" { end(): ArrayBuffer | Uint8Array; } - export const dns: { + const dns: { /** * Lookup the IP address for a hostname * @@ -741,9 +588,9 @@ declare module "bun" { * On macOS, it shouldn't be necessary to use "`getaddrinfo`" because * `"system"` uses the same API underneath (except non-blocking). * - * On windows, libuv's non-blocking DNS resolver is used by default, and + * On Windows, libuv's non-blocking DNS resolver is used by default, and * when specifying backends "system", "libc", or "getaddrinfo". The c-ares - * backend isn't currently supported on windows. + * backend isn't currently supported on Windows. */ backend?: "libc" | "c-ares" | "system" | "getaddrinfo"; }, @@ -775,7 +622,7 @@ declare module "bun" { * * This uses the same interface as {@link ArrayBufferSink}, but writes to a file or pipe. */ - export interface FileSink { + interface FileSink { /** * Write a chunk of data to the file. * @@ -831,7 +678,7 @@ declare module "bun" { unref(): void; } - export interface FileBlob extends BunFile {} + interface FileBlob extends BunFile {} /** * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files. * @@ -854,9 +701,8 @@ declare module "bun" { * "Hello, world!" * ); * ``` - * */ - export interface BunFile extends Blob { + interface BunFile extends Blob { /** * Offset any operation on the file starting at `begin` and ending at `end`. `end` is relative to 0 * @@ -870,9 +716,7 @@ declare module "bun" { */ slice(begin?: number, end?: number, contentType?: string): BunFile; - /** - * - */ + /** */ /** * Offset any operation on the file starting at `begin` * @@ -942,7 +786,7 @@ declare module "bun" { * } * ``` */ - export type MacroMap = Record>; + type MacroMap = Record>; /** * Hash a string or array buffer using Wyhash @@ -951,7 +795,7 @@ declare module "bun" { * @param data The data to hash. * @param seed The seed to use. */ - export const hash: (( + const hash: (( data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: number | bigint, ) => number | bigint) & @@ -989,15 +833,14 @@ declare module "bun" { ) => bigint; } - export type JavaScriptLoader = "jsx" | "js" | "ts" | "tsx"; + type JavaScriptLoader = "jsx" | "js" | "ts" | "tsx"; /** * Fast deep-equality check two objects. * * This also powers expect().toEqual in `bun:test` - * */ - export function deepEquals( + function deepEquals( a: any, b: any, /** @default false */ @@ -1010,7 +853,7 @@ declare module "bun" { * * This also powers expect().toMatchObject in `bun:test` */ - export function deepMatch(subset: unknown, a: unknown): boolean; + function deepMatch(subset: unknown, a: unknown): boolean; /** * tsconfig.json options supported by Bun @@ -1032,7 +875,7 @@ declare module "bun" { }; } - export interface TranspilerOptions { + interface TranspilerOptions { /** * Replace key with value. Value must be a JSON string. * @example @@ -1148,20 +991,19 @@ declare module "bun" { * const transpiler = new Bun.Transpiler(); * transpiler.transformSync(` * const App = () =>
Hello World
; - *export default App; + * export default App; * `); * // This outputs: * const output = ` * const App = () => jsx("div", { * children: "Hello World" * }, undefined, false, undefined, this); - *export default App; + * export default App; * ` * ``` - * */ - export class Transpiler { + class Transpiler { constructor(options?: TranspilerOptions); /** @@ -1174,7 +1016,6 @@ declare module "bun" { * Transpile code from TypeScript or JSX into valid JavaScript. * This function does not resolve imports. * @param code The code to transpile - * */ transformSync( code: StringOrBuffer, @@ -1186,7 +1027,6 @@ declare module "bun" { * This function does not resolve imports. * @param code The code to transpile * @param ctx An object to pass to macros - * */ transformSync(code: StringOrBuffer, ctx: object): string; @@ -1194,7 +1034,6 @@ declare module "bun" { * Transpile code from TypeScript or JSX into valid JavaScript. * This function does not resolve imports. * @param code The code to transpile - * */ transformSync(code: StringOrBuffer, loader?: JavaScriptLoader): string; @@ -1232,7 +1071,7 @@ declare module "bun" { scanImports(code: StringOrBuffer): Import[]; } - export type ImportKind = + type ImportKind = | "import-statement" | "require-call" | "require-resolve" @@ -1242,7 +1081,7 @@ declare module "bun" { | "internal" | "entry-point"; - export interface Import { + interface Import { path: string; kind: ImportKind; } @@ -1265,7 +1104,7 @@ declare module "bun" { splitting?: boolean; // default true, enable code splitting plugins?: BunPlugin[]; // manifest?: boolean; // whether to return manifest - external?: Array; + external?: string[]; publicPath?: string; define?: Record; // origin?: string; // e.g. http://mydomain.com @@ -1293,10 +1132,11 @@ declare module "bun" { // importSource?: string; // default: "react" // }; } - namespace Password { - export type AlgorithmLabel = "bcrypt" | "argon2id" | "argon2d" | "argon2i"; - export interface Argon2Algorithm { + namespace Password { + type AlgorithmLabel = "bcrypt" | "argon2id" | "argon2d" | "argon2i"; + + interface Argon2Algorithm { algorithm: "argon2id" | "argon2d" | "argon2i"; /** * Memory cost, which defines the memory usage, given in kibibytes. @@ -1309,7 +1149,7 @@ declare module "bun" { timeCost?: number; } - export interface BCryptAlgorithm { + interface BCryptAlgorithm { algorithm: "bcrypt"; /** * A number between 4 and 31. The default is 10. @@ -1348,7 +1188,7 @@ declare module "bun" { * console.log(verify); // true * ``` */ - export const password: { + const password: { /** * Verify a password against a previously hashed password. * @@ -1364,7 +1204,6 @@ declare module "bun" { * @throws If the algorithm is specified and does not match the hash * @throws If the algorithm is invalid * @throws if the hash is invalid - * */ verify( /** @@ -1523,7 +1362,7 @@ declare module "bun" { } interface BuildOutput { - outputs: Array; + outputs: BuildArtifact[]; success: boolean; logs: Array; } @@ -1549,7 +1388,19 @@ declare module "bun" { * } * ``` */ - type ServerWebSocketSendStatus = 0 | -1 | number; + type ServerWebSocketSendStatus = number; + + /** + * A state that represents if a WebSocket is connected. + * + * - `WebSocket.CONNECTING` is `0`, the connection is pending. + * - `WebSocket.OPEN` is `1`, the connection is established and `send()` is possible. + * - `WebSocket.CLOSING` is `2`, the connection is closing. + * - `WebSocket.CLOSED` is `3`, the connection is closed or couldn't be opened. + * + * @link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState + */ + type WebSocketReadyState = 0 | 1 | 2 | 3; /** * A fast WebSocket designed for servers. @@ -1582,7 +1433,7 @@ declare module "bun" { * } * }); */ - export interface ServerWebSocket { + interface ServerWebSocket { /** * Sends a message to the client. * @@ -1594,7 +1445,7 @@ declare module "bun" { * ws.send(new Uint8Array([1, 2, 3, 4])); */ send( - data: string | BufferSource, + data: string | Bun.BufferSource, compress?: boolean, ): ServerWebSocketSendStatus; @@ -1619,7 +1470,7 @@ declare module "bun" { * ws.send(new Uint8Array([1, 2, 3, 4]), true); */ sendBinary( - data: BufferSource, + data: Bun.BufferSource, compress?: boolean, ): ServerWebSocketSendStatus; @@ -1653,14 +1504,14 @@ declare module "bun" { * * @param data The data to send */ - ping(data?: string | BufferSource): ServerWebSocketSendStatus; + ping(data?: string | Bun.BufferSource): ServerWebSocketSendStatus; /** * Sends a pong. * * @param data The data to send */ - pong(data?: string | BufferSource): ServerWebSocketSendStatus; + pong(data?: string | Bun.BufferSource): ServerWebSocketSendStatus; /** * Sends a message to subscribers of the topic. @@ -1675,7 +1526,7 @@ declare module "bun" { */ publish( topic: string, - data: string | BufferSource, + data: string | Bun.BufferSource, compress?: boolean, ): ServerWebSocketSendStatus; @@ -1707,7 +1558,7 @@ declare module "bun" { */ publishBinary( topic: string, - data: BufferSource, + data: Bun.BufferSource, compress?: boolean, ): ServerWebSocketSendStatus; @@ -1873,7 +1724,7 @@ declare module "bun" { * }, * }); */ - export type WebSocketHandler = { + interface WebSocketHandler { /** * Called when the server receives an incoming message. * @@ -1994,22 +1845,21 @@ declare module "bun" { */ decompress?: WebSocketCompressor | boolean; }; - }; + } interface GenericServeOptions { /** - * * What URI should be used to make {@link Request.url} absolute? * * By default, looks at {@link hostname}, {@link port}, and whether or not SSL is enabled to generate one * * @example - *```js + * ```js * "http://my-app.com" * ``` * * @example - *```js + * ```js * "https://wongmjane.com/" * ``` * @@ -2035,7 +1885,7 @@ declare module "bun" { error?: ( this: Server, request: Errorlike, - ) => Response | Promise | undefined | void | Promise; + ) => Response | Promise | undefined | Promise; /** * Uniquely identify a server instance with an ID @@ -2053,8 +1903,8 @@ declare module "bun" { id?: string | null; } - export type AnyFunction = (..._: any[]) => any; - export interface ServeOptions extends GenericServeOptions { + type AnyFunction = (..._: any[]) => any; + interface ServeOptions extends GenericServeOptions { /** * What port should the server listen on? * @default process.env.PORT || "3000" @@ -2100,7 +1950,6 @@ declare module "bun" { * Handle HTTP requests * * Respond to {@link Request} objects with a {@link Response} object. - * */ fetch( this: Server, @@ -2109,7 +1958,7 @@ declare module "bun" { ): Response | Promise; } - export interface UnixServeOptions extends GenericServeOptions { + interface UnixServeOptions extends GenericServeOptions { /** * If set, the HTTP server will listen on a unix socket instead of a port. * (Cannot be used with hostname+port) @@ -2127,7 +1976,7 @@ declare module "bun" { ): Response | Promise; } - export interface WebSocketServeOptions + interface WebSocketServeOptions extends GenericServeOptions { /** * What port should the server listen on? @@ -2162,8 +2011,8 @@ declare module "bun" { * * @example * ```js - *import { serve } from "bun"; - *serve({ + * import { serve } from "bun"; + * serve({ * websocket: { * open: (ws) => { * console.log("Client connected"); @@ -2185,13 +2034,11 @@ declare module "bun" { * } * return new Response("Hello World"); * }, - *}); - *``` + * }); + * ``` * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade} * * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property - * - * */ websocket: WebSocketHandler; @@ -2199,7 +2046,6 @@ declare module "bun" { * Handle HTTP requests or upgrade them to a {@link ServerWebSocket} * * Respond to {@link Request} objects with a {@link Response} object. - * */ fetch( this: Server, @@ -2208,7 +2054,7 @@ declare module "bun" { ): Response | undefined | void | Promise; } - export interface UnixWebSocketServeOptions + interface UnixWebSocketServeOptions extends GenericServeOptions { /** * If set, the HTTP server will listen on a unix socket instead of a port. @@ -2223,8 +2069,8 @@ declare module "bun" { * * @example * ```js - *import { serve } from "bun"; - *serve({ + * import { serve } from "bun"; + * serve({ * websocket: { * open: (ws) => { * console.log("Client connected"); @@ -2246,13 +2092,11 @@ declare module "bun" { * } * return new Response("Hello World"); * }, - *}); - *``` + * }); + * ``` * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade} * * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property - * - * */ websocket: WebSocketHandler; @@ -2260,22 +2104,21 @@ declare module "bun" { * Handle HTTP requests or upgrade them to a {@link ServerWebSocket} * * Respond to {@link Request} objects with a {@link Response} object. - * */ fetch( this: Server, request: Request, server: Server, - ): Response | undefined | void | Promise; + ): Response | undefined | Promise; } - export interface TLSWebSocketServeOptions + interface TLSWebSocketServeOptions extends WebSocketServeOptions, TLSOptions { unix?: never; tls?: TLSOptions; } - export interface UnixTLSWebSocketServeOptions + interface UnixTLSWebSocketServeOptions extends UnixWebSocketServeOptions, TLSOptions { /** @@ -2285,7 +2128,7 @@ declare module "bun" { unix: string; tls?: TLSOptions; } - export interface Errorlike extends Error { + interface Errorlike extends Error { code?: string; errno?: number; syscall?: string; @@ -2389,7 +2232,7 @@ declare module "bun" { secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options } - export interface TLSServeOptions extends ServeOptions, TLSOptions { + interface TLSServeOptions extends ServeOptions, TLSOptions { /** * The keys are [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) hostnames. * The values are SSL options objects. @@ -2399,7 +2242,7 @@ declare module "bun" { tls?: TLSOptions; } - export interface UnixTLSServeOptions extends UnixServeOptions, TLSOptions { + interface UnixTLSServeOptions extends UnixServeOptions, TLSOptions { /** * The keys are [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) hostnames. * The values are SSL options objects. @@ -2409,7 +2252,7 @@ declare module "bun" { tls?: TLSOptions; } - export interface SocketAddress { + interface SocketAddress { /** * The IP address of the client. */ @@ -2435,7 +2278,7 @@ declare module "bun" { * * Powered by a fork of [uWebSockets](https://github.com/uNetworking/uWebSockets). Thank you @alexhultman. */ - export interface Server { + interface Server { /** * Stop listening to prevent new connections from being accepted. * @@ -2519,15 +2362,15 @@ declare module "bun" { * }); * ``` * What you pass to `data` is available on the {@link ServerWebSocket.data} property - * */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics upgrade( request: Request, options?: { /** * Send any additional headers while upgrading, like cookies */ - headers?: HeadersInit; + headers?: Bun.HeadersInit; /** * This value is passed to the {@link ServerWebSocket.data} property */ @@ -2613,7 +2456,6 @@ declare module "bun" { * stack traces instead of a generic 500 error. This makes debugging easier, * but development mode shouldn't be used in production or you will risk * leaking sensitive information. - * */ readonly development: boolean; @@ -2650,10 +2492,9 @@ declare module "bun" { * ); * ``` * @param path The path to the file (lazily loaded) - * */ // tslint:disable-next-line:unified-signatures - export function file(path: string | URL, options?: BlobPropertyBag): BunFile; + function file(path: string | URL, options?: BlobPropertyBag): BunFile; /** * `Blob` that leverages the fastest system calls available to operate on files. @@ -2672,7 +2513,7 @@ declare module "bun" { * @param path The path to the file as a byte buffer (the buffer is copied) */ // tslint:disable-next-line:unified-signatures - export function file( + function file( path: ArrayBufferLike | Uint8Array, options?: BlobPropertyBag, ): BunFile; @@ -2692,19 +2533,16 @@ declare module "bun" { * @param fileDescriptor The file descriptor of the file */ // tslint:disable-next-line:unified-signatures - export function file( - fileDescriptor: number, - options?: BlobPropertyBag, - ): BunFile; + function file(fileDescriptor: number, options?: BlobPropertyBag): BunFile; /** * Allocate a new [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) without zeroing the bytes. * * This can be 3.5x faster than `new Uint8Array(size)`, but if you send uninitialized memory to your users (even unintentionally), it can potentially leak anything recently in memory. */ - export function allocUnsafe(size: number): Uint8Array; + function allocUnsafe(size: number): Uint8Array; - export interface BunInspectOptions { + interface BunInspectOptions { colors?: boolean; depth?: number; sorted?: boolean; @@ -2717,8 +2555,8 @@ declare module "bun" { * * @param args */ - export function inspect(arg: any, options?: BunInspectOptions): string; - export namespace inspect { + function inspect(arg: any, options?: BunInspectOptions): string; + namespace inspect { /** * That can be used to declare custom inspect functions. */ @@ -2754,9 +2592,8 @@ declare module "bun" { * --- * * To close the file, set the array to `null` and it will be garbage collected eventually. - * */ - export function mmap(path: PathLike, opts?: MMapOptions): Uint8Array; + function mmap(path: PathLike, opts?: MMapOptions): Uint8Array; /** Write to stdout */ const stdout: BunFile; @@ -2771,7 +2608,7 @@ declare module "bun" { type StringLike = string | { toString(): string }; - interface semver { + interface Semver { /** * Test if the version satisfies the range. Stringifies both arguments. Returns `true` or `false`. */ @@ -2783,16 +2620,15 @@ declare module "bun" { */ order(v1: StringLike, v2: StringLike): -1 | 0 | 1; } - export const semver: semver; + var semver: Semver; - interface unsafe { + interface Unsafe { /** * Cast bytes to a `String` without copying. This is the fastest way to get a `String` from a `Uint8Array` or `ArrayBuffer`. * * **Only use this for ASCII strings**. If there are non-ascii characters, your application may crash and/or very confusing bugs will happen such as `"foo" !== "foo"`. * * **The input buffer must not be garbage collected**. That means you will need to hold on to it for the duration of the string's lifetime. - * */ arrayBufferToString(buffer: Uint8Array | ArrayBufferLike): string; @@ -2802,7 +2638,6 @@ declare module "bun" { * **The input must be a UTF-16 encoded string**. This API does no validation whatsoever. * * **The input buffer must not be garbage collected**. That means you will need to hold on to it for the duration of the string's lifetime. - * */ // tslint:disable-next-line:unified-signatures arrayBufferToString(buffer: Uint16Array): string; @@ -2827,7 +2662,7 @@ declare module "bun" { */ gcAggressionLevel(level?: 0 | 1 | 2): 0 | 1 | 2; } - export const unsafe: unsafe; + const unsafe: Unsafe; type DigestEncoding = "hex" | "base64"; @@ -2836,7 +2671,7 @@ declare module "bun" { * * Used for {@link console.log} */ - export const enableANSIColors: boolean; + const enableANSIColors: boolean; /** * What script launched bun? @@ -2845,7 +2680,7 @@ declare module "bun" { * * @example "/never-gonna-give-you-up.js" */ - export const main: string; + const main: string; /** * Manually trigger the garbage collector @@ -2856,7 +2691,7 @@ declare module "bun" { * * @param force Synchronously run the garbage collector */ - export function gc(force: boolean): void; + function gc(force: boolean): void; /** * JavaScriptCore engine's internal heap snapshot @@ -2888,24 +2723,24 @@ declare module "bun" { * After 14 weeks of consecutive uptime, this function * wraps */ - export function nanoseconds(): number; + function nanoseconds(): number; /** * Generate a heap snapshot for seeing where the heap is being used */ - export function generateHeapSnapshot(): HeapSnapshot; + function generateHeapSnapshot(): HeapSnapshot; /** * The next time JavaScriptCore is idle, clear unused memory and attempt to reduce the heap size. */ - export function shrink(): void; + function shrink(): void; /** * Open a file in your local editor. Auto-detects via `$VISUAL` || `$EDITOR` * * @param path path to open */ - export function openInEditor(path: string, options?: EditorOptions): void; + function openInEditor(path: string, options?: EditorOptions): void; interface EditorOptions { editor?: "vscode" | "subl"; @@ -2936,7 +2771,7 @@ declare module "bun" { * * @param hashInto `TypedArray` to write the hash into. Faster than creating a new one each time */ - digest(hashInto?: TypedArray): TypedArray; + digest(hashInto?: NodeJS.TypedArray): NodeJS.TypedArray; /** * Run the hash over the given data @@ -2945,7 +2780,10 @@ declare module "bun" { * * @param hashInto `TypedArray` to write the hash into. Faster than creating a new one each time */ - static hash(input: StringOrBuffer, hashInto?: TypedArray): TypedArray; + static hash( + input: StringOrBuffer, + hashInto?: NodeJS.TypedArray, + ): NodeJS.TypedArray; /** * Run the hash over the given data @@ -2973,10 +2811,9 @@ declare module "bun" { * * Used for `crypto.createHash()` */ - export class CryptoHasher { + class CryptoHasher { /** * The algorithm chosen to hash the data - * */ readonly algorithm: SupportedCryptoAlgorithms; @@ -3016,7 +2853,7 @@ declare module "bun" { * * @param hashInto `TypedArray` to write the hash into. Faster than creating a new one each time */ - digest(hashInto?: TypedArray): TypedArray; + digest(hashInto?: NodeJS.TypedArray): NodeJS.TypedArray; /** * Run the hash over the given data @@ -3028,8 +2865,8 @@ declare module "bun" { static hash( algorithm: SupportedCryptoAlgorithms, input: StringOrBuffer, - hashInto?: TypedArray, - ): TypedArray; + hashInto?: NodeJS.TypedArray, + ): NodeJS.TypedArray; /** * Run the hash over the given data @@ -3084,7 +2921,7 @@ declare module "bun" { * ``` * As always, you can use `Bun.sleep` or the imported `sleep` function interchangeably. */ - export function sleep(ms: number | Date): Promise; + function sleep(ms: number | Date): Promise; /** * Sleep the thread for a given number of milliseconds @@ -3093,10 +2930,9 @@ declare module "bun" { * * Internally, it calls [nanosleep(2)](https://man7.org/linux/man-pages/man2/nanosleep.2.html) */ - export function sleepSync(ms: number): void; + function sleepSync(ms: number): void; /** - * * Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions) * * @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` will be faster @@ -3111,12 +2947,14 @@ declare module "bun" { * ```bash * # You will need OpenSSL 3 or later * openssl sha512-256 /path/to/file - *``` + * ``` */ - export function sha(input: StringOrBuffer, hashInto?: TypedArray): TypedArray; + function sha( + input: StringOrBuffer, + hashInto?: NodeJS.TypedArray, + ): NodeJS.TypedArray; /** - * * Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions) * * @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` will be faster @@ -3131,16 +2969,16 @@ declare module "bun" { * ```bash * # You will need OpenSSL 3 or later * openssl sha512-256 /path/to/file - *``` + * ``` */ - export function sha(input: StringOrBuffer, encoding: DigestEncoding): string; + function sha(input: StringOrBuffer, encoding: DigestEncoding): string; /** * This is not the default because it's not cryptographically secure and it's slower than {@link SHA512} * * Consider using the ugly-named {@link SHA512_256} instead */ - export class SHA1 extends CryptoHashInterface { + class SHA1 extends CryptoHashInterface { constructor(); /** @@ -3148,7 +2986,7 @@ declare module "bun" { */ static readonly byteLength: 20; } - export class MD5 extends CryptoHashInterface { + class MD5 extends CryptoHashInterface { constructor(); /** @@ -3156,7 +2994,7 @@ declare module "bun" { */ static readonly byteLength: 16; } - export class MD4 extends CryptoHashInterface { + class MD4 extends CryptoHashInterface { constructor(); /** @@ -3164,7 +3002,7 @@ declare module "bun" { */ static readonly byteLength: 16; } - export class SHA224 extends CryptoHashInterface { + class SHA224 extends CryptoHashInterface { constructor(); /** @@ -3172,7 +3010,7 @@ declare module "bun" { */ static readonly byteLength: 28; } - export class SHA512 extends CryptoHashInterface { + class SHA512 extends CryptoHashInterface { constructor(); /** @@ -3180,7 +3018,7 @@ declare module "bun" { */ static readonly byteLength: 64; } - export class SHA384 extends CryptoHashInterface { + class SHA384 extends CryptoHashInterface { constructor(); /** @@ -3188,7 +3026,7 @@ declare module "bun" { */ static readonly byteLength: 48; } - export class SHA256 extends CryptoHashInterface { + class SHA256 extends CryptoHashInterface { constructor(); /** @@ -3199,7 +3037,7 @@ declare module "bun" { /** * See also {@link sha} */ - export class SHA512_256 extends CryptoHashInterface { + class SHA512_256 extends CryptoHashInterface { constructor(); /** @@ -3209,7 +3047,7 @@ declare module "bun" { } /** Compression options for `Bun.deflateSync` and `Bun.gzipSync` */ - export type ZlibCompressionOptions = { + interface ZlibCompressionOptions { /** * The compression level to use. Must be between `-1` and `9`. * - A value of `-1` uses the default compression level (Currently `6`) @@ -3276,7 +3114,7 @@ declare module "bun" { * Filtered data consists mostly of small values with a somewhat random distribution. */ strategy?: number; - }; + } /** * Compresses a chunk of data with `zlib` DEFLATE algorithm. @@ -3284,7 +3122,7 @@ declare module "bun" { * @param options Compression options to use * @returns The output buffer with the compressed data */ - export function deflateSync( + function deflateSync( data: Uint8Array, options?: ZlibCompressionOptions, ): Uint8Array; @@ -3294,7 +3132,7 @@ declare module "bun" { * @param options Compression options to use * @returns The output buffer with the compressed data */ - export function gzipSync( + function gzipSync( data: Uint8Array, options?: ZlibCompressionOptions, ): Uint8Array; @@ -3303,15 +3141,15 @@ declare module "bun" { * @param data The buffer of data to decompress * @returns The output buffer with the decompressed data */ - export function inflateSync(data: Uint8Array): Uint8Array; + function inflateSync(data: Uint8Array): Uint8Array; /** * Decompresses a chunk of data with `zlib` GUNZIP algorithm. * @param data The buffer of data to decompress * @returns The output buffer with the decompressed data */ - export function gunzipSync(data: Uint8Array): Uint8Array; + function gunzipSync(data: Uint8Array): Uint8Array; - export type Target = + type Target = /** * For generating bundles that are intended to be run by the Bun runtime. In many cases, * it isn't necessary to bundle server-side code; you can directly execute the source code @@ -3479,8 +3317,7 @@ declare module "bun" { args: OnResolveArgs, ) => | OnResolveResult - | Promise - | void + | Promise | undefined | null; @@ -3614,18 +3451,17 @@ declare module "bun" { * application. A future version of Bun may also support specifying plugins * via `bunfig.toml`. * - * * @example * A YAML loader plugin * * ```js - *Bun.plugin({ + * Bun.plugin({ * setup(builder) { * builder.onLoad({ filter: /\.yaml$/ }, ({path}) => ({ * loader: "object", * exports: require("js-yaml").load(fs.readFileSync(path, "utf8")) * })); - *}); + * }); * * // You can use require() * const {foo} = require("./file.yaml"); @@ -3668,7 +3504,7 @@ declare module "bun" { * end of the tick, when the event loop is idle, or sooner if the buffer is full. */ write( - data: string | BufferSource, + data: string | Bun.BufferSource, byteOffset?: number, byteLength?: number, ): number; @@ -3684,7 +3520,7 @@ declare module "bun" { * Use it to send your last message and close the connection. */ end( - data?: string | BufferSource, + data?: string | Bun.BufferSource, byteOffset?: number, byteLength?: number, ): number; @@ -3777,13 +3613,13 @@ declare module "bun" { interface TCPSocket extends Socket {} interface TLSSocket extends Socket {} - type BinaryTypeList = { + interface BinaryTypeList { arraybuffer: ArrayBuffer; buffer: Buffer; uint8array: Uint8Array; // TODO: DataView // dataview: DataView; - }; + } type BinaryType = keyof BinaryTypeList; interface SocketHandler< @@ -3854,7 +3690,6 @@ declare module "bun" { * Bun originally defaulted to `Uint8Array` but when dealing with network * data, it's more useful to be able to directly read from the bytes which * `Buffer` allows. - * */ binaryType?: BinaryType; } @@ -3887,7 +3722,6 @@ declare module "bun" { } /** - * * Create a TCP client that connects to a server * * @param options The options to use when creating the client @@ -3897,17 +3731,15 @@ declare module "bun" { * @param options.port The port to connect to * @param options.tls The TLS configuration object * @param options.unix The unix socket to connect to - * */ - export function connect( + function connect( options: TCPSocketConnectOptions, ): Promise>; - export function connect( + function connect( options: UnixSocketOptions, ): Promise>; /** - * * Create a TCP server that listens on a port * * @param options The options to use when creating the server @@ -3917,12 +3749,11 @@ declare module "bun" { * @param options.port The port to connect to * @param options.tls The TLS configuration object * @param options.unix The unix socket to connect to - * */ - export function listen( + function listen( options: TCPSocketListenOptions, ): TCPSocketListener; - export function listen( + function listen( options: UnixSocketOptions, ): UnixSocketListener; @@ -3975,7 +3806,6 @@ declare module "bun" { * Defaults to `process.env` as it was when the current Bun process launched. * * Changes to `process.env` at runtime won't automatically be reflected in the default value. For that, you can pass `process.env` explicitly. - * */ env?: Record; @@ -4193,7 +4023,7 @@ declare module "bun" { * If the signal code is unknown, it will return the original signal code * number, but that case should essentially never happen. */ - readonly signalCode: Signals | null; + readonly signalCode: NodeJS.Signals | null; /** * Has the process exited? @@ -4398,16 +4228,16 @@ declare module "bun" { "ignore" | "inherit" | null | undefined >; - export class FileSystemRouter { + class FileSystemRouter { /** * Create a new {@link FileSystemRouter}. * * @example * ```ts - *const router = new FileSystemRouter({ + * const router = new FileSystemRouter({ * dir: process.cwd() + "/pages", * style: "nextjs", - *}); + * }); * * const {params} = router.match("/blog/2020/01/01/hello-world"); * console.log(params); // {year: "2020", month: "01", day: "01", slug: "hello-world"} @@ -4449,7 +4279,7 @@ declare module "bun" { reload(): void; } - export interface MatchedRoute { + interface MatchedRoute { /** * A map of the parameters from the route * @@ -4480,60 +4310,188 @@ declare module "bun" { * @example * "0.2.0" */ - export const version: string; + const version: string; /** * The git sha at the time the currently-running version of Bun was compiled * @example * "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" */ - export const revision: string; + const revision: string; /** * Find the index of a newline character in potentially ill-formed UTF-8 text. * * This is sort of like readline() except without the IO. */ - export function indexOfLine( + function indexOfLine( buffer: ArrayBufferView | ArrayBufferLike, offset?: number, ): number; + + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = Bun.parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: { foo: true, bar: 'b' } [] + * ``` + * @param config Used to provide arguments for parsing and to configure the parser. + * @return The parsed command line arguments + */ + const parseArgs: typeof import("util").parseArgs; + + interface GlobScanOptions { + /** + * The root directory to start matching from. Defaults to `process.cwd()` + */ + cwd?: string; + + /** + * Allow patterns to match entries that begin with a period (`.`). + * + * @default false + */ + dot?: boolean; + + /** + * Return the absolute path for entries. + * + * @default false + */ + absolute?: boolean; + + /** + * Indicates whether to traverse descendants of symbolic link directories. + * + * @default false + */ + followSymlinks?: boolean; + + /** + * Throw an error when symbolic link is broken + * + * @default false + */ + throwErrorOnBrokenSymlink?: boolean; + + /** + * Return only files. + * + * @default true + */ + onlyFiles?: boolean; + } + + /** + * Match files using [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)). + * + * The supported pattern syntax for is: + * + * - `?` + * Matches any single character. + * - `*` + * Matches zero or more characters, except for path separators ('/' or '\'). + * - `**` + * Matches zero or more characters, including path separators. + * Must match a complete path segment, i.e. followed by a path separator or + * at the end of the pattern. + * - `[ab]` + * Matches one of the characters contained in the brackets. + * Character ranges (e.g. "[a-z]") are also supported. + * Use "[!ab]" or "[^ab]" to match any character *except* those contained + * in the brackets. + * - `{a,b}` + * Match one of the patterns contained in the braces. + * Any of the wildcards listed above can be used in the sub patterns. + * Braces may be nested up to 10 levels deep. + * - `!` + * Negates the result when at the start of the pattern. + * Multiple "!" characters negate the pattern multiple times. + * - `\` + * Used to escape any of the special characters above. + * + * @example + * ```js + * const glob = new Glob("*.{ts,tsx}"); + * const scannedFiles = await Array.fromAsync(glob.scan({ cwd: './src' })) + * ``` + */ + export class Glob { + constructor(pattern: string); + + /** + * Scan for files that match this glob pattern. Returns an async iterator. + * + * @example + * ```js + * const glob = new Glob("*.{ts,tsx}"); + * const scannedFiles = await Array.fromAsync(glob.scan({ cwd: './src' })) + * ``` + * + * @example + * ```js + * const glob = new Glob("*.{ts,tsx}"); + * for await (const path of glob.scan()) { + * // do something + * } + * ``` + */ + scan( + optionsOrCwd?: string | GlobScanOptions, + ): AsyncIterableIterator; + + /** + * Scan for files that match this glob pattern. Returns an iterator. + * + * @example + * ```js + * const glob = new Glob("*.{ts,tsx}"); + * const scannedFiles = Array.from(glob.scan({ cwd: './src' })) + * ``` + * + * @example + * ```js + * const glob = new Glob("*.{ts,tsx}"); + * for (const path of glob.scan()) { + * // do something + * } + * ``` + */ + scanSync(optionsOrCwd?: string | GlobScanOptions): IterableIterator; + + /** + * Match the glob against a string + * + * @example + * ```js + * const glob = new Glob("*.{ts,tsx}"); + * expect(glob.match('foo.ts')).toBeTrue(); + * ``` + */ + match(str: string): boolean; + } } -type TypedArray = - | Uint8Array - | Int8Array - | Uint8ClampedArray - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array; - -type TimeLike = string | number | Date; -type StringOrBuffer = string | TypedArray | ArrayBufferLike; -type PathLike = string | TypedArray | ArrayBufferLike | URL; -type PathOrFileDescriptor = PathLike | number; -type NoParamCallback = (err: ErrnoException | null) => void; -type BufferEncoding = - | "buffer" - | "utf8" - | "utf-8" - | "ascii" - | "utf16le" - | "ucs2" - | "ucs-2" - | "latin1" - | "binary" - | "hex" - | "base64" - | "base64url"; +type TypedArray = NodeJS.TypedArray; +// extends lib.dom.d.ts interface BufferEncodingOption { encoding?: BufferEncoding; } - -declare var Bun: typeof import("bun"); diff --git a/packages/bun-types/bun.lockb b/packages/bun-types/bun.lockb index 066d286b9e..f963cc99e4 100755 Binary files a/packages/bun-types/bun.lockb and b/packages/bun-types/bun.lockb differ diff --git a/packages/bun-types/child_process.d.ts b/packages/bun-types/child_process.d.ts deleted file mode 100644 index 58dc69f066..0000000000 --- a/packages/bun-types/child_process.d.ts +++ /dev/null @@ -1,1703 +0,0 @@ -/** - * 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 `env` is in the `options` object. Otherwise, `process.env.PATH` is - * used. If `options.env` is set without `PATH`, lookup on Unix is performed - * on a default search path search of `/usr/bin:/bin` (see your operating system's - * manual for execvpe/execvp), on Windows the current processes environment - * variable `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/v18.0.0/lib/child_process.js) - */ -declare module "child_process" { - import { SpawnOptions, ArrayBufferView } from "bun"; - import { ObjectEncodingOptions } from "node:fs"; - import { EventEmitter, Abortable } from "node:events"; - - import { Writable, Readable, Stream, Pipe } from "node:stream"; - import { URL } from "node:url"; - type Serializable = string | object | number | boolean | bigint; - // import * as net from "node:net"; - // type SendHandle = net.Socket | net.Server; - /** - * 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 { - spawn( - options: SpawnOptions.OptionsObject & { args: string[]; file?: string }, - ): ChildProcessWithoutNullStreams; - - /** - * 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 - 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; - /** - * 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 - * 2. disconnect - * 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: "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: "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: "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: "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: "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: "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, - 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 { - stdin: I; - stdout: O; - stderr: E; - readonly stdio: [ - I, - O, - E, - Readable | Writable | null | undefined, - // extra, no modification - Readable | Writable | null | undefined, // extra, no modification - ]; - } - interface MessageOptions { - keepOpen?: boolean | undefined; - } - type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; - type StdioOptions = - | IOType - | Array; - type SerializationType = "json" | "advanced"; - 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 | URL | undefined; - env?: Partial | undefined; - } - interface CommonOptions extends ProcessEnvOptions { - /** - * @default true - */ - windowsHide?: boolean | undefined; - /** - * @default 0 - */ - timeout?: number | undefined; - } - 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?: StdioPipeNamed | StdioPipe[] | undefined; - } - type StdioNull = "inherit" | "ignore" | Stream; - type StdioPipeNamed = "pipe" | "overlapped"; - type StdioPipe = undefined | null | StdioPipeNamed; - interface SpawnOptionsWithStdioTuple< - Stdin extends StdioNull | StdioPipe, - Stdout extends StdioNull | StdioPipe, - Stderr extends StdioNull | StdioPipe, - > extends SpawnOptions { - stdio: [Stdin, Stdout, Stderr]; - } - /** - * 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: 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: 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; - } - /** - * 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; - // `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; - // `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, - ): 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: (ObjectEncodingOptions & ExecOptions) | undefined | null, - callback?: ( - error: ExecException | null, - stdout: string | Buffer, - stderr: string | Buffer, - ) => void, - ): ChildProcess; - interface PromiseWithChild extends Promise { - child: ChildProcess; - } - 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?: (ObjectEncodingOptions & ExecOptions) | null, - ): PromiseWithChild<{ - stdout: string | Buffer; - stderr: string | Buffer; - }>; - } - 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; - } - interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: "buffer" | null; - } - interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - type ExecFileException = ExecException & 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: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - ): ChildProcess; - function execFile( - file: string, - args?: ReadonlyArray | 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, - ): 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, - ): 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, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - 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( - file: string, - args: ReadonlyArray | undefined | null, - 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: (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: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - callback: - | (( - error: ExecFileException | null, - stdout: string | Buffer, - stderr: string | Buffer, - ) => void) - | undefined - | null, - ): ChildProcess; - 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, - 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, Abortable { - execPath?: string | undefined; - execArgv?: string[] | undefined; - silent?: boolean | undefined; - stdio?: StdioOptions | undefined; - 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 | ArrayBufferView | undefined; - maxBuffer?: number | undefined; - encoding?: BufferEncoding | "buffer" | null | undefined; - } - interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding?: "buffer" | null | undefined; - } - interface SpawnSyncReturns { - pid: number; - output: Array; - stdout: T; - stderr: T; - status: number | null; - 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?: SpawnSyncOptions, - ): 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 CommonExecOptions extends CommonOptions { - input?: string | ArrayBufferView | undefined; - stdio?: StdioOptions | 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 CommonExecOptions { - shell?: boolean | string | undefined; - } - interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding?: "buffer" | null; // specify `null`. - } - /** - * 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/bun-types/console.d.ts b/packages/bun-types/console.d.ts deleted file mode 100644 index 08ca64c779..0000000000 --- a/packages/bun-types/console.d.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** - * 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/v18.0.0/lib/console.js) - */ -declare module "console" { - import console = require("node:console"); - export = console; -} -declare module "node:console" { - // import { InspectOptions } from "node:util"; - // global { - - /** - * 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) - */ - // import {Writable} from "node:stream"; - // namespace console { - // interface ConsoleConstructorOptions { - // stdout: Writable; - // stderr?: Writable | undefined; - // ignoreErrors?: boolean | undefined; - // colorMode?: boolean | "auto" | undefined; - // inspectOptions?: InspectOptions | undefined; - // /** - // * Set group indentation - // * @default 2 - // */ - // groupIndentation?: number | undefined; - // } - // interface ConsoleConstructor { - // prototype: Console; - // new (stdout: Writable, stderr?: Writable, ignoreErrors?: boolean): Console; - // new (options: ConsoleConstructorOptions): Console; - // } - // } - - // } - // const console: Console; - - export = console; -} diff --git a/packages/bun-types/constants.d.ts b/packages/bun-types/constants.d.ts deleted file mode 100644 index 6a672ad3de..0000000000 --- a/packages/bun-types/constants.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** @deprecated use constants property exposed by the relevant module instead. */ -declare module "constants" { - import { constants as osConstants, SignalConstants } from "node:os"; - import { constants as cryptoConstants } from "node:crypto"; - import { constants as fsConstants } from "node:fs"; - - const exp: typeof osConstants.errno & - typeof osConstants.priority & - SignalConstants & - typeof cryptoConstants & - typeof fsConstants; - export = exp; -} - -declare module "node:constants" { - import constants = require("constants"); - export = constants; -} diff --git a/packages/bun-types/crypto.d.ts b/packages/bun-types/crypto.d.ts deleted file mode 100644 index 79d724db2c..0000000000 --- a/packages/bun-types/crypto.d.ts +++ /dev/null @@ -1,3925 +0,0 @@ -/** - * 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/v18.0.0/lib/crypto.js) - */ -declare module "crypto" { - import { ArrayBufferView } from "bun"; - import * as stream from "node:stream"; - /** - * SPKAC is a Certificate Signing Request mechanism originally implemented by - * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). - * - * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects - * should not use this element anymore. - * - * The `crypto` module provides the `Certificate` class for working with SPKAC - * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC - * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally. - */ - class Certificate { - /** - * ```js - * const { Certificate } = await import('crypto'); - * const spkac = getSpkacSomehow(); - * const challenge = Certificate.exportChallenge(spkac); - * console.log(challenge.toString('utf8')); - * // Prints: the challenge as a UTF8 string - * ``` - * @param encoding The `encoding` of the `spkac` string. - * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. - */ - static exportChallenge(spkac: BinaryLike): Buffer; - /** - * ```js - * const { Certificate } = await import('crypto'); - * const spkac = getSpkacSomehow(); - * const publicKey = Certificate.exportPublicKey(spkac); - * console.log(publicKey); - * // Prints: the public key as - * ``` - * @param encoding The `encoding` of the `spkac` string. - * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. - */ - static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; - /** - * ```js - * import { Buffer } from 'buffer'; - * const { Certificate } = await import('crypto'); - * - * const spkac = getSpkacSomehow(); - * console.log(Certificate.verifySpkac(Buffer.from(spkac))); - * // Prints: true or false - * ``` - * @param encoding The `encoding` of the `spkac` string. - * @return `true` if the given `spkac` data structure is valid, `false` otherwise. - */ - static verifySpkac(spkac: ArrayBufferView): boolean; - /** - * @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: ArrayBufferView): boolean; - } - 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. */ - const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ - const SSL_OP_CIPHER_SERVER_PREFERENCE: number; - /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ - const SSL_OP_CISCO_ANYCONNECT: number; - /** Instructs OpenSSL to turn on cookie exchange. */ - const SSL_OP_COOKIE_EXCHANGE: number; - /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ - const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ - const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ - const SSL_OP_EPHEMERAL_RSA: number; - /** Allows initial connection to servers that do not support RI. */ - const SSL_OP_LEGACY_SERVER_CONNECT: number; - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - const SSL_OP_MICROSOFT_SESS_ID_BUG: number; - /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ - const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - const SSL_OP_NETSCAPE_CA_DN_BUG: number; - const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - /** Instructs OpenSSL to disable support for SSL/TLS compression. */ - const SSL_OP_NO_COMPRESSION: number; - const SSL_OP_NO_QUERY_MTU: number; - /** Instructs OpenSSL to always start a new session when performing renegotiation. */ - const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - const SSL_OP_NO_SSLv2: number; - const SSL_OP_NO_SSLv3: number; - const SSL_OP_NO_TICKET: number; - const SSL_OP_NO_TLSv1: number; - const SSL_OP_NO_TLSv1_1: number; - const SSL_OP_NO_TLSv1_2: number; - const SSL_OP_PKCS1_CHECK_1: number; - const SSL_OP_PKCS1_CHECK_2: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ - const SSL_OP_SINGLE_DH_USE: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ - const SSL_OP_SINGLE_ECDH_USE: number; - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - const SSL_OP_TLS_BLOCK_PADDING_BUG: number; - 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; - const ENGINE_METHOD_RAND: number; - const ENGINE_METHOD_EC: number; - const ENGINE_METHOD_CIPHERS: number; - const ENGINE_METHOD_DIGESTS: number; - const ENGINE_METHOD_PKEY_METHS: number; - 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; - const RSA_PKCS1_OAEP_PADDING: number; - const RSA_X931_PADDING: number; - const RSA_PKCS1_PSS_PADDING: number; - /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ - const RSA_PSS_SALTLEN_DIGEST: number; - /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ - 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 - * outputLength option can be used to specify the desired output length in bytes. - */ - 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` 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}`); - * } - * }); - * ``` - * @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` 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}`); - * } - * }); - * ``` - * @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" | "binary"; - 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 - * ``` - */ - class Hash extends stream.Transform { - private constructor(); - /** - * 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. - * ``` - * @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. - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): 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. - * @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 - * ``` - */ - 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. - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): 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. - * @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; - } - interface JwkKeyExportOptions { - format: "jwk"; - } - /** - * 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. - */ - 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) - * ``` - */ - // 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. - */ - 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. - */ - 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. - */ - 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. - */ - 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. - */ - 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 | ArrayBufferView; - type CipherKey = BinaryLike | KeyObject; - interface CipherCCMOptions extends stream.TransformOptions { - authTagLength: number; - } - interface CipherGCMOptions extends stream.TransformOptions { - authTagLength?: number | undefined; - } - 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 (e.g. `'aes-128-ccm'`) is used. 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. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On - * recent OpenSSL releases, `openssl list -cipher-algorithms` 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. - * @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; - /** - * 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 (e.g. `'aes-128-ccm'`) is used. 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. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On - * recent OpenSSL releases, `openssl list -cipher-algorithms` 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. - * @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); - * }); - * }); - * ``` - */ - 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. - * @param inputEncoding The `encoding` of the data. - * @param outputEncoding The `encoding` of the return value. - */ - update(data: BinaryLike): Buffer; - update(data: string, inputEncoding: Encoding): Buffer; - update( - data: 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. - * @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(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()`. - * @param [autoPadding=true] - * @return for method chaining. - */ - setAutoPadding(autoPadding?: boolean): this; - } - interface CipherCCM extends Cipher { - setAAD( - buffer: ArrayBufferView, - options: { - plaintextLength: number; - }, - ): this; - getAuthTag(): Buffer; - } - interface CipherGCM extends Cipher { - setAAD( - buffer: ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - getAuthTag(): Buffer; - } - interface CipherOCB extends Cipher { - setAAD( - buffer: 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 (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the - * authentication tag in bytes, see `CCM mode`. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * 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. - * @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; - /** - * 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 (e.g. `'aes-128-ccm'`) is used. 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. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On - * recent OpenSSL releases, `openssl list -cipher-algorithms` 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. - * @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 - * ``` - */ - 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. - * @param inputEncoding The `encoding` of the `data` string. - * @param outputEncoding The `encoding` of the return value. - */ - update(data: ArrayBufferView): Buffer; - update(data: string, inputEncoding: Encoding): Buffer; - update( - data: 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. - * @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(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()`. - * @param [autoPadding=true] - * @return for method chaining. - */ - setAutoPadding(auto_padding?: boolean): this; - } - interface DecipherCCM extends Decipher { - setAuthTag(buffer: ArrayBufferView): this; - setAAD( - buffer: ArrayBufferView, - options: { - plaintextLength: number; - }, - ): this; - } - interface DecipherGCM extends Decipher { - setAuthTag(buffer: ArrayBufferView): this; - setAAD( - buffer: ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - } - interface DecipherOCB extends Decipher { - setAuthTag(buffer: ArrayBufferView): this; - setAAD( - buffer: ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - } - interface PrivateKeyInput { - key: string | Buffer; - format?: KeyFormat | undefined; - type?: "pkcs1" | "pkcs8" | "sec1" | undefined; - passphrase?: string | Buffer | undefined; - } - interface PublicKeyInput { - key: string | Buffer; - format?: KeyFormat | undefined; - type?: "pkcs1" | "spki" | undefined; - } - /** - * 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 - * }); - * ``` - * @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 - * ``` - * @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. - */ - 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. - */ - 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`. - * @param encoding The string encoding when `key` is a string. - */ - function createSecretKey(key: ArrayBufferView): KeyObject; - 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. - * @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 - */ - padding?: number | undefined; - saltLength?: number | undefined; - dsaEncoding?: DSAEncoding | undefined; - } - interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} - interface SignKeyObjectInput extends SigningOptions { - key: KeyObject; - } - interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} - interface VerifyKeyObjectInput extends SigningOptions { - key: KeyObject; - } - type KeyLike = string | Buffer | KeyObject; - /** - * 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 - * ``` - */ - class Sign extends stream.Writable { - private constructor(); - /** - * 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. - * @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. - */ - 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. - * @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. - */ - 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. - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): Verify; - 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. - */ - verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, - signature: ArrayBufferView, - ): boolean; - verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, - signature: string, - signature_format?: BinaryToTextEncoding, - ): boolean; - } - /** - * 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. - * @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 | ArrayBufferView, - ): DiffieHellman; - function createDiffieHellman(prime: ArrayBufferView): DiffieHellman; - function createDiffieHellman( - prime: string, - primeEncoding: BinaryToTextEncoding, - ): DiffieHellman; - function createDiffieHellman( - prime: string, - primeEncoding: BinaryToTextEncoding, - generator: number | 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')); - * ``` - */ - 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. - * @param encoding The `encoding` of the return value. - */ - generateKeys(): Buffer; - generateKeys(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. - * @param inputEncoding The `encoding` of an `otherPublicKey` string. - * @param outputEncoding The `encoding` of the return value. - */ - computeSecret(otherPublicKey: ArrayBufferView): Buffer; - computeSecret( - otherPublicKey: string, - inputEncoding: BinaryToTextEncoding, - ): Buffer; - computeSecret( - otherPublicKey: ArrayBufferView, - 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. - * @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. - * @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. - * @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. - * @param encoding The `encoding` of the return value. - */ - getPrivateKey(): Buffer; - getPrivateKey(encoding: BinaryToTextEncoding): string; - /** - * 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`. - * @param encoding The `encoding` of the `publicKey` string. - */ - setPublicKey(publicKey: 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`. - * @param encoding The `encoding` of the `privateKey` string. - */ - setPrivateKey(privateKey: 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` - */ - verifyError: number; - } - /** - * 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); - * ``` - */ - function getDiffieHellman(groupName: string): DiffieHellman; - /** - * 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. - */ - 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}. - */ - 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. - * @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 248. `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}`); - * ``` - * @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')); - * ``` - * @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; - /** - * 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. - * @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; - parallelization?: number | undefined; - N?: number | undefined; - r?: number | undefined; - p?: number | undefined; - maxmem?: number | undefined; - } - /** - * 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' - * }); - * ``` - */ - 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' - * ``` - */ - function scryptSync( - password: BinaryLike, - salt: BinaryLike, - keylen: number, - options?: ScryptOptions, - ): Buffer; - interface RsaPublicKey { - key: KeyLike; - padding?: number | undefined; - } - interface RsaPrivateKey { - key: KeyLike; - passphrase?: string | undefined; - /** - * @default 'sha1' - */ - oaepHash?: string | undefined; - oaepLabel?: 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. - */ - function publicEncrypt( - key: RsaPublicKey | RsaPrivateKey | KeyLike, - buffer: 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. - */ - function publicDecrypt( - key: RsaPublicKey | RsaPrivateKey | KeyLike, - buffer: 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`. - */ - function privateDecrypt( - privateKey: RsaPrivateKey | KeyLike, - buffer: 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`. - */ - function privateEncrypt( - privateKey: RsaPrivateKey | KeyLike, - buffer: ArrayBufferView, - ): Buffer; - /** - * ```js - * const { - * getCiphers - * } = await import('crypto'); - * - * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] - * ``` - * @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', ...] - * ``` - * @return An array with the names of the supported elliptic curves. - */ - function getCurves(): string[]; - /** - * @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; - /** - * ```js - * const { - * getHashes - * } = await import('crypto'); - * - * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] - * ``` - * @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 - * ``` - */ - 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')); - * ``` - * @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", - ): 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. - * @param encoding The `encoding` of the return value. - * @param [format='uncompressed'] - */ - generateKeys(): Buffer; - generateKeys( - encoding: BinaryToTextEncoding, - format?: ECDHKeyFormat, - ): 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. - * @param inputEncoding The `encoding` of the `otherPublicKey` string. - * @param outputEncoding The `encoding` of the return value. - */ - computeSecret(otherPublicKey: ArrayBufferView): Buffer; - computeSecret( - otherPublicKey: string, - inputEncoding: BinaryToTextEncoding, - ): Buffer; - computeSecret( - otherPublicKey: 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. - * @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. - * @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; - /** - * 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. - * @param encoding The `encoding` of the `privateKey` string. - */ - setPrivateKey(privateKey: ArrayBufferView): void; - setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; - } - /** - * 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. - */ - 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. An error is thrown if `a` and `b` have - * different byte lengths. - * - * 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. - */ - function timingSafeEqual(a: ArrayBufferView, b: ArrayBufferView): boolean; - /** @deprecated since v10.0.0 */ - const DEFAULT_ENCODING: BufferEncoding; - type KeyType = - | "rsa" - | "rsa-pss" - | "dsa" - | "ec" - | "ed25519" - | "ed448" - | "x25519" - | "x448"; - type KeyFormat = "pem" | "der"; - interface BasePrivateKeyEncodingOptions { - format: T; - cipher?: string | undefined; - passphrase?: string | undefined; - } - interface KeyPairKeyObjectResult { - publicKey: KeyObject; - privateKey: KeyObject; - } - // eslint-disable-next-line @typescript-eslint/no-empty-interface - interface ED25519KeyPairKeyObjectOptions {} - // eslint-disable-next-line @typescript-eslint/no-empty-interface - interface ED448KeyPairKeyObjectOptions {} - // eslint-disable-next-line @typescript-eslint/no-empty-interface - interface X25519KeyPairKeyObjectOptions {} - // eslint-disable-next-line @typescript-eslint/no-empty-interface - interface X448KeyPairKeyObjectOptions {} - interface ECKeyPairKeyObjectOptions { - /** - * 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; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs1" | "pkcs8"; - }; - } - interface RSAPSSKeyPairOptions< - PubF extends KeyFormat, - PrivF extends KeyFormat, - > { - /** - * 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 - */ - modulusLength: number; - /** - * Size of q in bits - */ - divisorLength: number; - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface ECKeyPairOptions { - /** - * Name of the curve to use. - */ - namedCurve: string; - publicKeyEncoding: { - type: "pkcs1" | "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "sec1" | "pkcs8"; - }; - } - interface ED25519KeyPairOptions< - PubF extends KeyFormat, - PrivF extends KeyFormat, - > { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface ED448KeyPairOptions< - PubF extends KeyFormat, - PrivF extends KeyFormat, - > { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface X25519KeyPairOptions< - PubF extends KeyFormat, - PrivF extends KeyFormat, - > { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface X448KeyPairOptions< - PubF extends KeyFormat, - PrivF extends KeyFormat, - > { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface KeyPairSyncResult< - T1 extends string | Buffer, - T2 extends string | Buffer, - > { - publicKey: T1; - privateKey: T2; - } - /** - * 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. - * @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: "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: 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?: 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?: 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?: 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?: X448KeyPairKeyObjectOptions, - ): KeyPairKeyObjectResult; - /** - * 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. - * @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; - }>; - function __promisify__( - type: "rsa", - options: RSAKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "rsa", - options: RSAKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "rsa", - 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; - }>; - function __promisify__( - type: "dsa", - options: DSAKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "dsa", - options: DSAKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "dsa", - 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; - }>; - function __promisify__( - type: "ec", - options: ECKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "ec", - options: ECKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "ec", - 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; - }>; - function __promisify__( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "ed25519", - 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; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "ed448", - 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; - }>; - function __promisify__( - type: "x25519", - options: X25519KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "x25519", - 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; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "x448", - 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 {@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. - */ - function sign( - algorithm: string | null | undefined, - data: ArrayBufferView, - key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - ): Buffer; - function sign( - algorithm: string | null | undefined, - data: ArrayBufferView, - key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - callback: (error: Error | null, data: Buffer) => void, - ): void; - /** - * 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 {@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. - */ - function verify( - algorithm: string | null | undefined, - data: ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, - signature: ArrayBufferView, - ): boolean; - function verify( - algorithm: string | null | undefined, - data: ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, - signature: ArrayBufferView, - 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). - */ - 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. - * @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' - * }); - * ``` - * @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' - * ``` - * @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; - } - /** - */ - 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. - */ - function randomUUID(options?: RandomUUIDOptions): string; - interface X509CheckOptions { - /** - * @default 'always' - */ - subject: "always" | "never"; - /** - * @default true - */ - wildcards: boolean; - /** - * @default true - */ - partialWildcards: boolean; - /** - * @default false - */ - multiLabelWildcards: boolean; - /** - * @default false - */ - singleLabelSubdomains: boolean; - } - type LargeNumberLike = - | 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. - * @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. - * @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`. - * @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`. - * @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; - /** - * 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. - */ - export const webcrypto: Crypto; -} -declare module "node:crypto" { - export * from "crypto"; -} diff --git a/packages/bun-types/diagnostics_channel.d.ts b/packages/bun-types/diagnostics_channel.d.ts deleted file mode 100644 index afc63c922b..0000000000 --- a/packages/bun-types/diagnostics_channel.d.ts +++ /dev/null @@ -1,254 +0,0 @@ -/** - * The `node: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 'node: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. - * @since Bun v0.7.2 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) - */ -declare module "diagnostics_channel" { - import { AsyncLocalStorage } from "async_hooks"; - // type AsyncLocalStorage = import("async_hooks").AsyncLocalStorage; - type ChannelListener = (message: unknown, name: string | symbol) => void; - /** - * 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 'node:diagnostics_channel'; - * - * if (diagnostics_channel.hasSubscribers('my-channel')) { - * // There are subscribers, prepare and publish message - * } - * ``` - * @since Bun v0.7.2 - * @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 publish to 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 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * ``` - * @since Bun v0.7.2 - * @param name The channel name - * @return The named channel object - */ - function channel(name: string | symbol): Channel; - /** - * 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 'node:diagnostics_channel'; - * - * diagnostics_channel.subscribe('my-channel', (message, name) => { - * // Received data - * }); - * ``` - * @since Bun v0.7.2 - * @param name The channel name - * @param onMessage The handler to receive channel messages - */ - function subscribe(name: string | symbol, onMessage: ChannelListener): void; - /** - * Remove a message handler previously registered to this channel with {@link subscribe}. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * function onMessage(message, name) { - * // Received data - * } - * - * diagnostics_channel.subscribe('my-channel', onMessage); - * - * diagnostics_channel.unsubscribe('my-channel', onMessage); - * ``` - * @since Bun v0.7.2 - * @param name The channel name - * @param onMessage The previous subscribed handler to remove - * @return `true` if the handler was found, `false` otherwise. - */ - function unsubscribe( - name: string | symbol, - onMessage: ChannelListener, - ): boolean; - /** - * The class `Channel` represents an individual named channel within the data - * pipeline. It is used 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 Bun v0.7.2 - */ - 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 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * if (channel.hasSubscribers) { - * // There are subscribers, prepare and publish message - * } - * ``` - * @since Bun v0.7.2 - */ - 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 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.publish({ - * some: 'message', - * }); - * ``` - * @since Bun v0.7.2 - * @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 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.subscribe((message, name) => { - * // Received data - * }); - * ``` - * @since Bun v0.7.2 - * @deprecated Use {@link subscribe(name, onMessage)} - * @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 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * function onMessage(message, name) { - * // Received data - * } - * - * channel.subscribe(onMessage); - * - * channel.unsubscribe(onMessage); - * ``` - * @since Bun v0.7.2 - * @deprecated Use {@link unsubscribe(name, onMessage)} - * @param onMessage The previous subscribed handler to remove - * @return `true` if the handler was found, `false` otherwise. - */ - unsubscribe(onMessage: ChannelListener): void; - bindStore( - store: AsyncLocalStorage, - transform?: TransformCallback, - ): void; - unbindStore(store: AsyncLocalStorage): void; - runStores( - context: unknown, - fn: (...args: unknown[]) => unknown, - receiver?: unknown, - ...args: unknown[] - ): any; - } - type TransformCallback = (value: T) => unknown; - type TracingChannelSubscribers = { - start?: ChannelListener; - end?: ChannelListener; - asyncStart?: ChannelListener; - asyncEnd?: ChannelListener; - error?: ChannelListener; - }; - type TracingChannels = { - start: Channel; - end: Channel; - asyncStart: Channel; - asyncEnd: Channel; - error: Channel; - }; - class TracingChannel implements TracingChannels { - readonly start: Channel; - readonly end: Channel; - readonly asyncStart: Channel; - readonly asyncEnd: Channel; - readonly error: Channel; - subscribe(subscribers: TracingChannelSubscribers): void; - unsubscribe(subscribers: TracingChannelSubscribers): boolean; - traceSync( - fn: (...values: any[]) => T, - context?: any, - thisArg?: any, - ...args: any[] - ): any; - tracePromise( - fn: (...values: any[]) => Promise, - context?: any, - thisArg?: any, - ...args: any[] - ): Promise; - traceCallback( - fn: (...values: any[]) => T, - position?: number, - context?: any, - thisArg?: any, - ...args: any[] - ): any; - } - function tracingChannel( - nameOrChannels: string | TracingChannels, - ): TracingChannel; -} - -declare module "node:diagnostics_channel" { - export * from "diagnostics_channel"; -} diff --git a/packages/bun-types/dns.d.ts b/packages/bun-types/dns.d.ts deleted file mode 100644 index 8eee833612..0000000000 --- a/packages/bun-types/dns.d.ts +++ /dev/null @@ -1,880 +0,0 @@ -/** - * 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/v18.0.0/lib/dns.js) - */ -declare module "dns" { - import * as dnsPromises from "node:dns/promises"; - // Supported getaddrinfo flags. - export const ADDRCONFIG: number; - export const V4MAPPED: number; - /** - * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as - * well as IPv4 mapped IPv6 addresses. - */ - export const ALL: number; - export interface LookupOptions { - family?: number | undefined; - // hints?: number | undefined; - // all?: boolean | undefined; - /** - * @default true - */ - // verbatim?: boolean | undefined; - } - export interface LookupOneOptions extends LookupOptions { - // all?: false | undefined; - } - export interface LookupAllOptions extends LookupOptions { - // all: true; - } - export interface LookupAddress { - address: string; - family: number; - } - /** - * 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: ErrnoException | null, - address: string, - family: number, - ) => void, - ): void; - // export function lookup( - // hostname: string, - // options: LookupOneOptions, - // callback: ( - // err: ErrnoException | null, - // address: string, - // family: number, - // ) => void, - // ): void; - // export function lookup( - // hostname: string, - // options: LookupAllOptions, - // callback: ( - // err: ErrnoException | null, - // addresses: LookupAddress[], - // ) => void, - // ): void; - export function lookup( - hostname: string, - options: LookupOptions, - callback: ( - err: ErrnoException | null, - address: string | LookupAddress[], - family: number, - ) => void, - ): void; - export function lookup( - hostname: string, - callback: ( - err: 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; - // } - /** - * 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: ErrnoException | null, - hostname: string, - service: string, - ) => void, - ): void; - // export namespace lookupService { - // function __promisify__( - // address: string, - // port: number, - // ): Promise<{ - // hostname: string; - // service: string; - // }>; - // } - export interface ResolveOptions { - ttl: boolean; - } - export interface ResolveWithTtlOptions extends ResolveOptions { - ttl: true; - } - export interface RecordWithTtl { - address: string; - ttl: number; - } - /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ - export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; - export interface AnyARecord extends RecordWithTtl { - type: "A"; - } - export interface AnyAaaaRecord extends RecordWithTtl { - type: "AAAA"; - } - 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; - } - export interface AnyMxRecord extends MxRecord { - type: "MX"; - } - export interface NaptrRecord { - flags: string; - service: string; - regexp: string; - replacement: string; - order: number; - preference: number; - } - export interface AnyNaptrRecord extends NaptrRecord { - type: "NAPTR"; - } - export interface SoaRecord { - nsname: string; - hostmaster: string; - serial: number; - refresh: number; - retry: number; - expire: number; - minttl: number; - } - export interface AnySoaRecord extends SoaRecord { - type: "SOA"; - } - export interface SrvRecord { - priority: number; - weight: number; - port: number; - name: string; - } - export interface AnySrvRecord extends SrvRecord { - type: "SRV"; - } - export interface AnyTxtRecord { - type: "TXT"; - entries: string[]; - } - export interface AnyNsRecord { - type: "NS"; - value: string; - } - export interface AnyPtrRecord { - type: "PTR"; - value: string; - } - export interface AnyCnameRecord { - type: "CNAME"; - value: string; - } - 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: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "A", - callback: (err: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "AAAA", - callback: (err: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "ANY", - callback: (err: ErrnoException | null, addresses: AnyRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "CNAME", - callback: (err: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "MX", - callback: (err: ErrnoException | null, addresses: MxRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "NAPTR", - callback: (err: ErrnoException | null, addresses: NaptrRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "NS", - callback: (err: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "PTR", - callback: (err: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "SOA", - callback: (err: ErrnoException | null, addresses: SoaRecord) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "SRV", - callback: (err: ErrnoException | null, addresses: SrvRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "TXT", - callback: (err: ErrnoException | null, addresses: string[][]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: string, - callback: ( - err: ErrnoException | null, - addresses: - | string[] - | MxRecord[] - | NaptrRecord[] - | SoaRecord - | SrvRecord[] - | string[][] - | AnyRecord[], - ) => void, - ): void; - 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< - | string[] - | MxRecord[] - | NaptrRecord[] - | SoaRecord - | SrvRecord[] - | string[][] - | AnyRecord[] - >; - } - /** - * 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: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve4( - hostname: string, - options: ResolveWithTtlOptions, - callback: (err: ErrnoException | null, addresses: RecordWithTtl[]) => void, - ): void; - export function resolve4( - hostname: string, - options: ResolveOptions, - callback: ( - err: 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; - // } - /** - * 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: ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve6( - hostname: string, - options: ResolveWithTtlOptions, - callback: (err: ErrnoException | null, addresses: RecordWithTtl[]) => void, - ): void; - export function resolve6( - hostname: string, - options: ResolveOptions, - callback: ( - err: 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; - // } - /** - * 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: ErrnoException | null, addresses: string[]) => void, - ): void; - export namespace resolveCname { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function - * will contain an array of certification authority authorization records - * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). - * @since v15.0.0, v14.17.0 - */ - export function resolveCaa( - hostname: string, - callback: (err: 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: ErrnoException | null, addresses: MxRecord[]) => void, - ): void; - export namespace resolveMx { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, addresses: NaptrRecord[]) => void, - ): void; - export namespace resolveNaptr { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, addresses: string[]) => void, - ): void; - export namespace resolveNs { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, addresses: string[]) => void, - ): void; - export namespace resolvePtr { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, address: SoaRecord) => void, - ): void; - export namespace resolveSoa { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, addresses: SrvRecord[]) => void, - ): void; - export namespace resolveSrv { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, addresses: string[][]) => void, - ): void; - export namespace resolveTxt { - function __promisify__(hostname: string): Promise; - } - /** - * 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: ErrnoException | null, addresses: AnyRecord[]) => void, - // ): void; - // export namespace resolveAny { - // function __promisify__(hostname: string): Promise; - // } - /** - * 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: 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} and `dnsPromises.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 v16.4.0, v14.18.0 - * @param order must be `'ipv4first'` or `'verbatim'`. - */ - // export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; - // Error codes - export const NODATA: string; - export const FORMERR: string; - export const SERVFAIL: string; - export const NOTFOUND: string; - export const NOTIMP: string; - export const REFUSED: string; - export const BADQUERY: string; - export const BADNAME: string; - export const BADFAMILY: string; - export const BADRESP: string; - export const CONNREFUSED: string; - export const TIMEOUT: string; - export const EOF: string; - export const FILE: string; - export const NOMEM: string; - export const DESTRUCTION: string; - export const BADSTR: string; - export const BADFLAGS: string; - export const NONAME: string; - export const BADHINTS: string; - export const NOTINITIALIZED: string; - export const LOADIPHLPAPI: string; - export const ADDRGETNETWORKPARAMS: string; - export const CANCELLED: string; - export interface ResolverOptions { - timeout?: number | undefined; - /** - * @default 4 - */ - tries?: number; - } - /** - * An independent resolver for DNS requests. - * - * Creating a new resolver uses the default server settings. Setting - * the servers used for a resolver using `resolver.setServers()` does not affect - * other resolvers: - * - * ```js - * const { Resolver } = require('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; - 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; - /** - * The resolver instance will send its requests from the specified IP address. - * This allows programs to specify outbound interfaces when used on multi-homed - * systems. - * - * If a v4 or v6 address is not specified, it is set to the default, and the - * operating system will choose a local address automatically. - * - * The resolver will use the v4 local address when making requests to IPv4 DNS - * servers, and the v6 local address when making requests to IPv6 DNS servers. - * The `rrtype` of resolution requests has no impact on the local address used. - * @since v15.1.0, v14.17.0 - * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. - * @param [ipv6='::0'] A string representation of an IPv6 address. - */ - // setLocalAddress(ipv4?: string, ipv6?: string): void; - // setServers: typeof setServers; - } - export { dnsPromises as promises }; -} -declare module "node:dns" { - export * from "dns"; -} diff --git a/packages/bun-types/dns/promises.d.ts b/packages/bun-types/dns/promises.d.ts deleted file mode 100644 index 7f5faad751..0000000000 --- a/packages/bun-types/dns/promises.d.ts +++ /dev/null @@ -1,402 +0,0 @@ -/** - * 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 resolveSrv(hostname: string): Promise; - function resolve(hostname: string, rrtype: "TXT"): Promise; - function resolve( - hostname: string, - rrtype: string, - ): Promise< - | string[] - | MxRecord[] - | NaptrRecord[] - | SoaRecord - | SrvRecord[] - | string[][] - | AnyRecord[] - >; - /** - * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 - * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). - * @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, v14.17.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 `dns.lookup()` and `dnsPromises.lookup()`. The value could be: - * - * * `ipv4first`: sets default `verbatim` `false`. - * * `verbatim`: sets default `verbatim` `true`. - * - * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have - * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the - * default dns orders in workers. - * @since v16.4.0, v14.18.0 - * @param order must be `'ipv4first'` or `'verbatim'`. - */ - // 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/bun-types/domain.d.ts b/packages/bun-types/domain.d.ts deleted file mode 100644 index e1df3fc7ad..0000000000 --- a/packages/bun-types/domain.d.ts +++ /dev/null @@ -1,170 +0,0 @@ -/** - * **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 - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/domain.js) - */ -declare module "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 | number): 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 | number): 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" { - export * from "domain"; -} diff --git a/packages/bun-types/events.d.ts b/packages/bun-types/events.d.ts deleted file mode 100644 index ce69f4e0c2..0000000000 --- a/packages/bun-types/events.d.ts +++ /dev/null @@ -1,661 +0,0 @@ -/** - * 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/v18.0.0/lib/events.js) - */ -declare module "events" { - interface EventEmitterOptions { - /** - * Enables automatic capturing of promise rejection. - */ - captureRejections?: boolean | undefined; - } - interface NodeEventTarget { - once(eventName: string | symbol, listener: (...args: any[]) => void): this; - } - interface DOMEventTarget { - addEventListener( - eventName: string, - listener: (...args: any[]) => void, - opts?: { - once: boolean; - }, - ): any; - } - interface StaticEventEmitterOptions { - signal?: AbortSignal | undefined; - } - interface EventEmitter< - Events extends Record = Record< - string | symbol, - any[] - >, - > { - /** - * Alias for `emitter.on(eventName, listener)`. - */ - addListener( - eventName: K, - listener: (...args: Events[K]) => 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 - * ``` - * @param eventName The name of the event. - * @param listener The callback function - */ - on( - eventName: K, - listener: (...args: Events[K]) => 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 - * ``` - * @param eventName The name of the event. - * @param listener The callback function - */ - once( - eventName: K, - listener: (...args: Events[K]) => 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. - */ - removeListener( - eventName: K, - listener: (...args: Events[K]) => void, - ): this; - /** - * Alias for `emitter.removeListener()`. - */ - off( - eventName: K, - listener: (...args: Events[K]) => 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. - */ - removeAllListeners(event?: keyof Events): 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. - */ - 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}. - */ - getMaxListeners(): number; - /** - * 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] ] - * ``` - */ - listeners(eventName: keyof Events): 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'); - * ``` - */ - rawListeners(eventName: keyof Events): 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 - * ``` - */ - emit(eventName: K, ...args: Events[K]): boolean; - /** - * Returns the number of listeners listening to the event named `eventName`. - * @param eventName The name of the event being listened for - */ - listenerCount(eventName: keyof Events): 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. - * @param eventName The name of the event. - * @param listener The callback function - */ - prependListener( - eventName: K, - listener: (...args: Events[K]) => 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. - * @param eventName The name of the event. - * @param listener The callback function - */ - prependOnceListener( - eventName: K, - listener: (...args: Events[K]) => 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) ] - * ``` - */ - eventNames(): Array; - } - /** - * 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: - */ - class EventEmitter { - constructor(options?: EventEmitterOptions); - /** - * 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! - * ``` - */ - 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()); - * ``` - * @param eventName The name of the event being listened for - * @return that iterates `eventName` events emitted by the `emitter` - */ - static on( - emitter: 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 - * ``` - * @deprecated Since v3.2.0 - Use `listenerCount` instead. - * @param emitter The emitter to query - * @param eventName The event name - */ - static listenerCount( - emitter: 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] - * } - * ``` - */ - static getEventListeners( - emitter: DOMEventTarget | EventEmitter, - name: string | symbol, - ): Function[]; - /** - * ```js - * const { - * setMaxListeners, - * EventEmitter - * } = require('events'); - * - * const target = new EventTarget(); - * const emitter = new EventEmitter(); - * - * setMaxListeners(5, target, emitter); - * ``` - * @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 - * `'error'` listeners are called. - * - * Installing a listener using this symbol does not change the behavior once an - * `'error'` event is emitted, therefore the process will still crash if no - * regular `'error'` listener is installed. - */ - static readonly errorMonitor: unique symbol; - static readonly captureRejectionSymbol: unique symbol; - /** - * Sets or gets the default captureRejection value for all emitters. - */ - static captureRejections: boolean; - static defaultMaxListeners: number; - } - import internal = require("node:events"); - namespace EventEmitter { - // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 - export { internal as EventEmitter }; - export interface Abortable { - /** - * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. - */ - signal?: AbortSignal | undefined; - } - } - export = EventEmitter; -} -declare module "node:events" { - import events = require("events"); - export = events; -} diff --git a/packages/bun-types/ffi.d.ts b/packages/bun-types/ffi.d.ts index 1207f74c46..37b3094605 100644 --- a/packages/bun-types/ffi.d.ts +++ b/packages/bun-types/ffi.d.ts @@ -13,10 +13,9 @@ * that convert JavaScript types to C types and back. Internally, * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks * goes to Fabrice Bellard and TinyCC maintainers for making this possible. - * */ declare module "bun:ffi" { - export enum FFIType { + enum FFIType { char = 0, /** * 8-bit signed integer @@ -174,7 +173,6 @@ declare module "bun:ffi" { /** * 32-bit signed integer - * */ int32_t = 5, @@ -270,8 +268,6 @@ declare module "bun:ffi" { * bool * _Bool * ``` - * - * */ bool = 11, @@ -309,7 +305,6 @@ declare module "bun:ffi" { * ```c * void * ``` - * */ void = 13, @@ -317,7 +312,6 @@ declare module "bun:ffi" { * When used as a `returns`, this will automatically become a {@link CString}. * * When used in `args` it is equivalent to {@link FFIType.pointer} - * */ cstring = 14, @@ -329,7 +323,6 @@ declare module "bun:ffi" { * * In JavaScript, this could be number or it could be BigInt, depending on what * value is passed in. - * */ i64_fast = 15, @@ -341,14 +334,13 @@ declare module "bun:ffi" { * * In JavaScript, this could be number or it could be BigInt, depending on what * value is passed in. - * */ u64_fast = 16, function = 17, } type UNTYPED = never; - export type Pointer = number & {}; + type Pointer = number & {}; interface FFITypeToArgsType { [FFIType.char]: number; @@ -374,10 +366,10 @@ declare module "bun:ffi" { [FFIType.float]: number; [FFIType.f32]: number; [FFIType.bool]: boolean; - [FFIType.ptr]: TypedArray | Pointer | CString | null; - [FFIType.pointer]: TypedArray | Pointer | CString | null; - [FFIType.void]: void; - [FFIType.cstring]: TypedArray | Pointer | CString | null; + [FFIType.ptr]: NodeJS.TypedArray | Pointer | CString | null; + [FFIType.pointer]: NodeJS.TypedArray | Pointer | CString | null; + [FFIType.void]: undefined; + [FFIType.cstring]: NodeJS.TypedArray | Pointer | CString | null; [FFIType.i64_fast]: number | bigint; [FFIType.u64_fast]: number | bigint; [FFIType.function]: Pointer | JSCallback; // cannot be null @@ -408,7 +400,7 @@ declare module "bun:ffi" { [FFIType.bool]: boolean; [FFIType.ptr]: Pointer | null; [FFIType.pointer]: Pointer | null; - [FFIType.void]: void; + [FFIType.void]: undefined; [FFIType.cstring]: CString; [FFIType.i64_fast]: number | bigint; [FFIType.u64_fast]: number | bigint; @@ -447,7 +439,7 @@ declare module "bun:ffi" { ["callback"]: FFIType.pointer; // for now } - export type FFITypeOrString = FFIType | keyof FFITypeStringToType; + type FFITypeOrString = FFIType | keyof FFITypeStringToType; interface FFIFunction { /** @@ -547,9 +539,7 @@ declare module "bun:ffi" { // */ // export function callback(ffi: FFIFunction, cb: Function): number; - export interface Library< - Fns extends Readonly>>, - > { + interface Library>>> { symbols: ConvertFns; /** @@ -568,6 +558,7 @@ declare module "bun:ffi" { ? FFITypeStringToType[T] : never; + // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type type _Narrow = [U] extends [T] ? U : Extract; type Narrow = | _Narrow @@ -584,11 +575,13 @@ declare module "bun:ffi" { [K in keyof Fns]: ( ...args: Fns[K]["args"] extends infer A extends readonly FFITypeOrString[] ? { [L in keyof A]: FFITypeToArgsType[ToFFIType] } - : [unknown] extends [Fns[K]["args"]] + : // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type + [unknown] extends [Fns[K]["args"]] ? [] : never - ) => [unknown] extends [Fns[K]["returns"]] - ? void + ) => // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type + [unknown] extends [Fns[K]["returns"]] + ? undefined : FFITypeToReturnsType[ToFFIType>]; }; @@ -617,9 +610,8 @@ declare module "bun:ffi" { * that convert JavaScript types to C types and back. Internally, * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks * goes to Fabrice Bellard and TinyCC maintainers for making this possible. - * */ - export function dlopen>>( + function dlopen>>( name: string, symbols: Fns, ): Library; @@ -649,11 +641,8 @@ declare module "bun:ffi" { * that convert JavaScript types to C types and back. Internally, * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks * goes to Fabrice Bellard and TinyCC maintainers for making this possible. - * */ - export function CFunction( - fn: FFIFunction & { ptr: Pointer }, - ): CallableFunction & { + function CFunction(fn: FFIFunction & { ptr: Pointer }): CallableFunction & { /** * Free the memory allocated by the wrapping function */ @@ -710,9 +699,8 @@ declare module "bun:ffi" { * that convert JavaScript types to C types and back. Internally, * bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks * goes to Fabrice Bellard and TinyCC maintainers for making this possible. - * */ - export function linkSymbols>>( + function linkSymbols>>( symbols: Fns, ): Library; @@ -729,9 +717,8 @@ declare module "bun:ffi" { * thing to do safely. Passing an invalid pointer can crash the program and * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! - * */ - export function toBuffer( + function toBuffer( ptr: Pointer, byteOffset?: number, byteLength?: number, @@ -751,13 +738,13 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function toArrayBuffer( + function toArrayBuffer( ptr: Pointer, byteOffset?: number, byteLength?: number, ): ArrayBuffer; - export namespace read { + namespace read { /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -770,7 +757,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function u8(ptr: Pointer, byteOffset?: number): number; + function u8(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -783,7 +770,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function i8(ptr: Pointer, byteOffset?: number): number; + function i8(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -796,7 +783,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function u16(ptr: Pointer, byteOffset?: number): number; + function u16(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -809,7 +796,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function i16(ptr: Pointer, byteOffset?: number): number; + function i16(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -822,7 +809,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function u32(ptr: Pointer, byteOffset?: number): number; + function u32(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -835,7 +822,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function i32(ptr: Pointer, byteOffset?: number): number; + function i32(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -848,7 +835,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function f32(ptr: Pointer, byteOffset?: number): number; + function f32(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -861,7 +848,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function u64(ptr: Pointer, byteOffset?: number): bigint; + function u64(ptr: Pointer, byteOffset?: number): bigint; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -874,7 +861,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function i64(ptr: Pointer, byteOffset?: number): bigint; + function i64(ptr: Pointer, byteOffset?: number): bigint; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -887,7 +874,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function f64(ptr: Pointer, byteOffset?: number): number; + function f64(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -900,7 +887,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function ptr(ptr: Pointer, byteOffset?: number): number; + function ptr(ptr: Pointer, byteOffset?: number): number; /** * The read function behaves similarly to DataView, * but it's usually faster because it doesn't need to create a DataView or ArrayBuffer. @@ -913,7 +900,7 @@ declare module "bun:ffi" { * reading beyond the bounds of the pointer will crash the program or cause * undefined behavior. Use with care! */ - export function intptr(ptr: Pointer, byteOffset?: number): number; + function intptr(ptr: Pointer, byteOffset?: number): number; } /** @@ -941,10 +928,9 @@ declare module "bun:ffi" { * // Do something with rawPtr * } * ``` - * */ - export function ptr( - view: TypedArray | ArrayBufferLike | DataView, + function ptr( + view: NodeJS.TypedArray | ArrayBufferLike | DataView, byteOffset?: number, ): Pointer; @@ -971,7 +957,7 @@ declare module "bun:ffi" { * undefined behavior. Use with care! */ - export class CString extends String { + class CString extends String { /** * Get a string from a UTF-8 encoded C string * If `byteLength` is not provided, the string is assumed to be null-terminated. @@ -980,7 +966,6 @@ declare module "bun:ffi" { * @param byteOffset bytes to skip before reading * @param byteLength bytes to read * - * * @example * ```js * var ptr = lib.symbols.getVersion(); @@ -1023,7 +1008,7 @@ declare module "bun:ffi" { /** * Pass a JavaScript function to FFI (Foreign Function Interface) */ - export class JSCallback { + class JSCallback { /** * Enable a JavaScript callback function to be passed to C with bun:ffi * @@ -1058,8 +1043,8 @@ declare module "bun:ffi" { * You probably won't need this unless there's a bug in the FFI bindings * generator or you're just curious. */ - export function viewSource(symbols: Symbols, is_callback?: false): string[]; - export function viewSource(callback: FFIFunction, is_callback: true): string; + function viewSource(symbols: Symbols, is_callback?: false): string[]; + function viewSource(callback: FFIFunction, is_callback: true): string; /** * Platform-specific file extension name for dynamic libraries @@ -1076,5 +1061,5 @@ declare module "bun:ffi" { * "so" // linux * ``` */ - export const suffix: string; + const suffix: string; } diff --git a/packages/bun-types/fs.d.ts b/packages/bun-types/fs.d.ts deleted file mode 100644 index e028383ca1..0000000000 --- a/packages/bun-types/fs.d.ts +++ /dev/null @@ -1,4346 +0,0 @@ -/** - * 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 and callback - * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). - */ -declare module "fs" { - import * as stream from "stream"; - import type EventEmitter from "events"; - import type { SystemError, ArrayBufferView } from "bun"; - interface ObjectEncodingOptions { - encoding?: BufferEncoding | null | undefined; - } - - const promises: Awaited; - type EncodingOption = - | ObjectEncodingOptions - | BufferEncoding - | undefined - | null; - type OpenMode = number | string; - type Mode = number | string; - type SimlinkType = "symlink" | "junction" | undefined | null; - interface StatsBase { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: T; - ino: T; - mode: T; - nlink: T; - uid: T; - gid: T; - rdev: T; - size: T; - blksize: T; - blocks: T; - atimeMs: T; - mtimeMs: T; - ctimeMs: T; - birthtimeMs: T; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - 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.0.67 - */ - 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 v0.0.67 - */ - class Dirent { - /** - * Returns `true` if the `fs.Dirent` object describes a regular file. - * @since v0.0.67 - */ - isFile(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a file system - * directory. - * @since v0.0.67 - */ - isDirectory(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a block device. - * @since v0.0.67 - */ - isBlockDevice(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a character device. - * @since v0.0.67 - */ - isCharacterDevice(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a symbolic link. - * @since v0.0.67 - */ - isSymbolicLink(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a first-in-first-out - * (FIFO) pipe. - * @since v0.0.67 - */ - isFIFO(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a socket. - * @since v0.0.67 - */ - 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 v0.0.67 - */ - name: string; - } - - /** - * 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.67 - */ - function rename( - oldPath: PathLike, - newPath: PathLike, - callback: NoParamCallback, - ): void; - // namespace rename { - // /** - // * Asynchronous rename(2) - Change the name or location of a file or directory. - // * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - // * URL support is _experimental_. - // * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - // * URL support is _experimental_. - // */ - // function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - // } - /** - * 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.0.67 - */ - function renameSync(oldPath: PathLike, newPath: PathLike): void; - /** - * 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.0.67 - * @param [len=0] - */ - 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. - */ - function truncate(path: PathLike, callback: NoParamCallback): void; - // namespace truncate { - // /** - // * 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`. - // */ - // function __promisify__(path: PathLike, len?: number | null): Promise; - // } - /** - * 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.0.67 - * @param [len=0] - */ - function truncateSync(path: PathLike, len?: number | null): void; - /** - * 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.0.67 - * @param [len=0] - */ - 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. - */ - function ftruncate(fd: number, callback: NoParamCallback): void; - // namespace ftruncate { - // /** - // * Asynchronous ftruncate(2) - Truncate a file to a specified length. - // * @param fd A file descriptor. - // * @param len If not specified, defaults to `0`. - // */ - // function __promisify__(fd: number, len?: number | null): Promise; - // } - /** - * Truncates the file descriptor. Returns `undefined`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link ftruncate}. - * @since v0.0.67 - * @param [len=0] - */ - function ftruncateSync(fd: number, len?: number | null): void; - /** - * 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.0.67 - */ - function chown( - path: PathLike, - uid: number, - gid: number, - callback: NoParamCallback, - ): void; - // namespace chown { - // /** - // * Asynchronous chown(2) - Change ownership of a file. - // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - // */ - // function __promisify__( - // path: PathLike, - // uid: number, - // gid: number - // ): Promise; - // } - /** - * 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.0.67 - */ - function chownSync(path: PathLike, uid: number, gid: number): void; - /** - * 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.0.67 - */ - function fchown( - fd: number, - uid: number, - gid: number, - callback: NoParamCallback, - ): void; - // namespace fchown { - // /** - // * Asynchronous fchown(2) - Change ownership of a file. - // * @param fd A file descriptor. - // */ - // function __promisify__(fd: number, uid: number, gid: number): Promise; - // } - /** - * 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.0.67 - * @param uid The file's new owner's user id. - * @param gid The file's new group's group id. - */ - function fchownSync(fd: number, uid: number, gid: number): void; - /** - * 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. - */ - function lchown( - path: PathLike, - uid: number, - gid: number, - callback: NoParamCallback, - ): void; - // namespace lchown { - // /** - // * 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. - // */ - // function __promisify__( - // path: PathLike, - // uid: number, - // gid: number - // ): Promise; - // } - /** - * 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. - */ - function lchownSync(path: PathLike, uid: number, gid: number): void; - /** - * 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 v0.0.67 - */ - function lutimes( - path: PathLike, - atime: TimeLike, - mtime: TimeLike, - callback: NoParamCallback, - ): void; - // namespace lutimes { - // /** - // * 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. - // */ - // 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 {@link lutimes}. - * @since v0.0.67 - */ - function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; - /** - * 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.0.67 - */ - function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - // namespace chmod { - // /** - // * Asynchronous chmod(2) - Change permissions of a file. - // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - // * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - // */ - // function __promisify__(path: PathLike, mode: Mode): Promise; - // } - /** - * 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.0.67 - */ - function chmodSync(path: PathLike, mode: Mode): void; - /** - * 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.0.67 - */ - function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; - // namespace fchmod { - // /** - // * 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. - // */ - // function __promisify__(fd: number, mode: Mode): Promise; - // } - /** - * 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.0.67 - */ - function fchmodSync(fd: number, mode: Mode): void; - /** - * 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 - */ - function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - // /** @deprecated */ - // namespace lchmod { - // /** - // * 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. - // */ - // function __promisify__(path: PathLike, mode: Mode): Promise; - // } - /** - * 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 - */ - function lchmodSync(path: PathLike, mode: Mode): void; - /** - * 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.67 - */ - function stat( - path: PathLike, - callback: (err: SystemError | null, stats: Stats) => void, - ): void; - function stat( - path: PathLike, - options: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: SystemError | null, stats: Stats) => void, - ): void; - function stat( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - callback: (err: SystemError | null, stats: BigIntStats) => void, - ): void; - function stat( - path: PathLike, - options: StatOptions | undefined, - callback: (err: SystemError | null, stats: Stats | BigIntStats) => void, - ): void; - // 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 - // ): Promise; - // } - // tslint:disable-next-line:unified-signatures - interface StatSyncFn extends Function { - // tslint:disable-next-line:unified-signatures - (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; - // tslint:disable-next-line:unified-signatures - ( - path: PathLike, - // tslint:disable-next-line:unified-signatures - 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. - */ - var statSync: StatSyncFn; - /** - * 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.0.67 - */ - function fstat( - fd: number, - callback: (err: SystemError | null, stats: Stats) => void, - ): void; - function fstat( - fd: number, - options: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: SystemError | null, stats: Stats) => void, - ): void; - function fstat( - fd: number, - options: StatOptions & { - bigint: true; - }, - callback: (err: SystemError | null, stats: BigIntStats) => void, - ): void; - function fstat( - fd: number, - options: StatOptions | undefined, - callback: (err: SystemError | null, stats: Stats | BigIntStats) => void, - ): void; - // 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 - // ): Promise; - // } - /** - * Retrieves 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.0.67 - */ - function fstatSync( - fd: number, - options?: StatOptions & { - bigint?: false | undefined; - }, - ): Stats; - function fstatSync( - fd: number, - options: StatOptions & { - bigint: true; - }, - ): BigIntStats; - function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; - /** - * 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.0.67 - */ - function lstat( - path: PathLike, - callback: (err: SystemError | null, stats: Stats) => void, - ): void; - function lstat( - path: PathLike, - options: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: SystemError | null, stats: Stats) => void, - ): void; - function lstat( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - callback: (err: SystemError | null, stats: BigIntStats) => void, - ): void; - function lstat( - path: PathLike, - options: StatOptions | undefined, - callback: (err: SystemError | null, stats: Stats | BigIntStats) => void, - ): void; - // 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 - // ): 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. - */ - var lstatSync: StatSyncFn; - /** - * 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.0.67 - */ - function link( - existingPath: PathLike, - newPath: PathLike, - callback: NoParamCallback, - ): void; - // namespace link { - // /** - // * 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. - // */ - // function __promisify__( - // existingPath: PathLike, - // newPath: PathLike - // ): Promise; - // } - /** - * 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.0.67 - */ - function linkSync(existingPath: PathLike, newPath: PathLike): void; - /** - * 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.0.67 - */ - function symlink( - target: PathLike, - path: PathLike, - type: SimlinkType, - 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. - */ - function symlink( - target: PathLike, - path: PathLike, - callback: NoParamCallback, - ): void; - // namespace symlink { - // /** - // * 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. - // */ - // function __promisify__( - // target: PathLike, - // path: PathLike, - // type?: string | null - // ): Promise; - // type Type = "dir" | "file" | "junction"; - // } - /** - * Returns `undefined`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link symlink}. - * @since v0.0.67 - */ - function symlinkSync( - target: PathLike, - path: PathLike, - type?: SimlinkType, - ): void; - /** - * 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.0.67 - */ - function readlink( - path: PathLike, - options: EncodingOption, - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function readlink( - path: PathLike, - options: BufferEncodingOption, - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function readlink( - path: PathLike, - options: EncodingOption, - // tslint:disable-next-line:unified-signatures - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function readlink( - path: PathLike, - callback: (err: SystemError | null, linkString: string) => void, - ): void; - // 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?: 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?: EncodingOption - // ): Promise; - // } - /** - * 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.0.67 - */ - 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. - */ - 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. - */ - function readlinkSync( - path: PathLike, - options?: EncodingOption, - ): string | Buffer; - /** - * 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.0.67 - */ - function realpath( - path: PathLike, - options: EncodingOption, - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function realpath( - path: PathLike, - options: BufferEncodingOption, - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function realpath( - path: PathLike, - options: EncodingOption, - // tslint:disable-next-line:unified-signatures - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function realpath( - path: PathLike, - callback: (err: SystemError | null, resolvedPath: string) => void, - ): void; - // 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?: 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?: 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 v0.0.67 - // */ - // function native( - // path: PathLike, - // options: EncodingOption, - // // tslint:disable-next-line:unified-signatures - // callback: (err: SystemError | null, resolvedPath: string) => void - // ): void; - // function native( - // path: PathLike, - // options: BufferEncodingOption, - // // tslint:disable-next-line:unified-signatures - // callback: (err: SystemError | null, resolvedPath: Buffer) => void - // ): void; - // function native( - // path: PathLike, - // options: EncodingOption, - // // tslint:disable-next-line:unified-signatures - // callback: (err: SystemError | null, resolvedPath: string | Buffer) => void - // ): void; - // function native( - // path: PathLike, - // callback: (err: SystemError | null, resolvedPath: string) => void - // ): void; - // } - /** - * Returns the resolved pathname. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link realpath}. - * @since v0.0.67 - */ - 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. - */ - 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. - */ - function realpathSync( - path: PathLike, - options?: EncodingOption, - ): string | Buffer; - namespace realpathSync { - function native(path: PathLike, options?: EncodingOption): string; - function native(path: PathLike, options: BufferEncodingOption): Buffer; - function native(path: PathLike, options?: EncodingOption): string | Buffer; - } - /** - * 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.67 - */ - function unlink(path: PathLike, callback: NoParamCallback): void; - // namespace unlink { - // /** - // * 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. - // */ - // function __promisify__(path: PathLike): Promise; - // } - /** - * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. - * @since v0.0.67 - */ - function unlinkSync(path: PathLike): void; - interface RmDirOptions { - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number | undefined; - /** - * @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 operations are retried on failure. - * @default false - */ - recursive?: boolean | undefined; - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number | undefined; - } - /** - * 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.67 - */ - function rmdir(path: PathLike, callback: NoParamCallback): void; - function rmdir( - path: PathLike, - options: RmDirOptions, - callback: NoParamCallback, - ): void; - // namespace rmdir { - // /** - // * Asynchronous rmdir(2) - delete a directory. - // * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - // */ - // function __promisify__( - // path: PathLike, - // options?: RmDirOptions - // ): Promise; - // } - /** - * 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.0.67 - */ - function rmdirSync(path: PathLike, options?: RmDirOptions): void; - interface RmOptions { - /** - * When `true`, exceptions will be ignored if `path` does not exist. - * @default false - */ - force?: boolean | undefined; - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number | undefined; - /** - * If `true`, perform a recursive directory removal. In - * recursive mode, operations are retried on failure. - * @default false - */ - recursive?: boolean | undefined; - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number | undefined; - } - /** - * 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; - 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). Returns `undefined`. - * @since v14.14.0 - */ - export function rmSync(path: PathLike, options?: RmOptions): void; - export interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * If a folder was created, the path to the first created folder will be returned. - * @default false - */ - recursive?: boolean | undefined; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777 - */ - mode?: Mode | undefined; - } - interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * If a folder was created, the path to the first created folder will be returned. - * @default false - */ - recursive?: boolean | undefined; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777 - */ - 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.0.67 - */ - function mkdir( - path: PathLike, - options: MakeDirectoryOptions & { - recursive: true; - }, - callback: (err: SystemError | 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`. - */ - 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. - * @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, - // tslint:disable-next-line:unified-signatures - options: Mode | MakeDirectoryOptions | null | undefined, - callback: (err: SystemError | 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. - */ - function mkdir(path: PathLike, callback: NoParamCallback): void; - // namespace mkdir { - // /** - // * 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: 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; - // /** - // * 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 | 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.0.67 - */ - - 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`. - */ - 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. - * @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 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 v0.0.67 - */ - function mkdtemp( - prefix: string, - options: EncodingOption, - callback: (err: SystemError | 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. - */ - function mkdtemp( - prefix: string, - options: - | "buffer" - | { - encoding: "buffer"; - }, - callback: (err: SystemError | 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. - */ - function mkdtemp( - prefix: string, - options: EncodingOption, - // tslint:disable-next-line:unified-signatures - callback: (err: SystemError | 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. - */ - // tslint:disable-next-line:unified-signatures - function mkdtemp( - prefix: string, - callback: (err: SystemError | null, folder: string) => void, - ): void; - // 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?: 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?: EncodingOption - // ): Promise; - // } - /** - * 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 v0.0.67 - */ - 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. - */ - 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. - */ - function mkdtempSync( - prefix: string, - options?: EncodingOption, - ): string | Buffer; - /** - * 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.0.67 - */ - function readdir( - path: PathLike, - options: - | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | BufferEncoding - | undefined - | null, - callback: (err: SystemError | 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 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; - recursive?: boolean | undefined; - } - | "buffer", - callback: (err: SystemError | 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. - * @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: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }) - | BufferEncoding - | undefined - | null, - callback: (err: SystemError | 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. - */ - function readdir( - path: PathLike, - callback: (err: SystemError | 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. - */ - function readdir( - path: PathLike, - options: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - callback: (err: SystemError | null, files: Dirent[]) => void, - ): void; - // 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; - // recursive?: boolean | 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; - // recursive?: boolean | 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?: - // | (ObjectEncodingOptions & { - // withFileTypes?: false | undefined; - // recursive?: boolean | 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: ObjectEncodingOptions & { - // withFileTypes: true; - // recursive?: boolean | undefined; - // } - // ): 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.0.67 - */ - function readdirSync( - path: PathLike, - options?: - | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - recursive?: boolean | 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. - */ - function readdirSync( - path: PathLike, - options: - | { - encoding: "buffer"; - withFileTypes?: false | undefined; - recursive?: boolean | 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. - */ - function readdirSync( - path: PathLike, - options?: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | 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. - */ - function readdirSync( - path: PathLike, - options: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - ): Dirent[]; - /** - * 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.67 - */ - function close(fd: number, callback?: NoParamCallback): void; - // namespace close { - // /** - // * Asynchronous close(2) - close a file descriptor. - // * @param fd A file descriptor. - // */ - // function __promisify__(fd: number): Promise; - // } - /** - * 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.0.67 - */ - function closeSync(fd: number): void; - /** - * 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.67 - * @param [flags='r'] See `support of file system `flags``. - * @param [mode=0o666] - */ - function open( - path: PathLike, - flags: OpenMode, - mode: Mode | undefined | null, - callback: (err: SystemError | 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. - */ - function open( - path: PathLike, - flags: OpenMode, - callback: (err: SystemError | null, fd: number) => void, - ): void; - // namespace open { - // /** - // * 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`. - // */ - // function __promisify__( - // path: PathLike, - // flags: OpenMode, - // mode?: Mode | null - // ): Promise; - // } - /** - * Returns an integer representing the file descriptor. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link open}. - * @since v0.0.67 - * @param [flags='r'] - * @param [mode=0o666] - */ - function openSync( - path: PathLike, - flags: OpenMode, - mode?: Mode | null, - ): 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.0.67 - */ - function utimes( - path: PathLike, - atime: TimeLike, - mtime: TimeLike, - callback: NoParamCallback, - ): void; - // namespace utimes { - // /** - // * 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. - // */ - // function __promisify__( - // path: PathLike, - // atime: TimeLike, - // mtime: TimeLike - // ): Promise; - // } - /** - * Returns `undefined`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link utimes}. - * @since v0.0.67 - */ - function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; - /** - * Change the file system timestamps of the object referenced by the supplied file - * descriptor. See {@link utimes}. - * @since v0.0.67 - */ - function futimes( - fd: number, - atime: TimeLike, - mtime: TimeLike, - callback: NoParamCallback, - ): void; - // namespace futimes { - // /** - // * 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. - // */ - // function __promisify__( - // fd: number, - // atime: TimeLike, - // mtime: TimeLike - // ): Promise; - // } - /** - * Synchronous version of {@link futimes}. Returns `undefined`. - * @since v0.0.67 - */ - function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; - /** - * 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.0.67 - */ - function fsync(fd: number, callback: NoParamCallback): void; - // namespace fsync { - // /** - // * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - // * @param fd A file descriptor. - // */ - // function __promisify__(fd: number): Promise; - // } - /** - * 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.0.67 - */ - function fsyncSync(fd: number): void; - /** - * 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. - * - * 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.67 - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: ( - err: SystemError | null, - written: number, - buffer: TBuffer, - ) => void, - ): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param 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`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: ( - err: SystemError | null, - written: number, - buffer: TBuffer, - ) => void, - ): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - callback: ( - err: SystemError | null, - written: number, - buffer: TBuffer, - ) => void, - ): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - function write( - fd: number, - buffer: TBuffer, - callback: ( - err: SystemError | null, - written: number, - buffer: TBuffer, - ) => 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. - * @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( - fd: number, - string: string, - position: number | undefined | null, - encoding: BufferEncoding | undefined | null, - callback: (err: SystemError | 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. - * @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( - fd: number, - string: string, - position: number | undefined | null, - callback: (err: SystemError | 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. - */ - function write( - fd: number, - string: string, - callback: (err: SystemError | null, written: number, str: string) => void, - ): void; - // namespace write { - // /** - // * 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. - // */ - // function __promisify__( - // fd: number, - // buffer?: TBuffer, - // offset?: number, - // length?: number, - // 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. - // * @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 __promisify__( - // fd: number, - // string: string, - // position?: number | null, - // encoding?: BufferEncoding | null - // ): Promise<{ - // bytesWritten: number; - // buffer: string; - // }>; - // } - /** - * 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.0.67 - * @return The number of bytes written. - */ - function writeSync( - fd: number, - buffer: 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. - * @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 writeSync( - fd: number, - string: string, - position?: number | null, - encoding?: BufferEncoding | null, - ): number; - type ReadPosition = number | bigint; - interface ReadSyncOptions { - /** - * @default 0 - */ - offset?: number | undefined; - /** - * @default `length of buffer` - */ - length?: number | undefined; - /** - * @default null - */ - position?: ReadPosition | null | undefined; - } - interface ReadAsyncOptions - extends ReadSyncOptions { - buffer?: TBuffer; - } - /** - * 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.67 - * @param buffer The buffer that the data will be written to. - * @param offset The position in `buffer` to write the data to. - * @param length The number of bytes to read. - * @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. - */ - function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: ReadPosition | null, - callback: ( - err: SystemError | null, - bytesRead: number, - buffer: TBuffer, - ) => void, - ): void; - /** - * Similar to the above `fs.read` function, this version takes an optional `options` object. - * If not otherwise specified in an `options` object, - * `buffer` defaults to `Buffer.alloc(16384)`, - * `offset` defaults to `0`, - * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 - * `position` defaults to `null` - * @since v0.0.67 - */ - function read( - fd: number, - options: ReadAsyncOptions, - callback: ( - err: SystemError | null, - bytesRead: number, - buffer: TBuffer, - ) => void, - ): void; - function read( - fd: number, - callback: ( - err: SystemError | null, - bytesRead: number, - buffer: ArrayBufferView, - ) => void, - ): void; - // namespace 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. - // */ - // function __promisify__( - // fd: number, - // buffer: TBuffer, - // offset: number, - // length: number, - // position: number | null - // ): Promise<{ - // bytesRead: number; - // buffer: TBuffer; - // }>; - // function __promisify__( - // fd: number, - // options: ReadAsyncOptions - // ): Promise<{ - // bytesRead: number; - // buffer: TBuffer; - // }>; - // function __promisify__(fd: number): Promise<{ - // bytesRead: number; - // buffer: ArrayBufferView; - // }>; - // } - - // TODO: Add AbortSignal support - // tslint:disable-next-line:no-empty-interface - interface Abortable {} - - /** - * Returns the number of `bytesRead`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link read}. - * @since v0.0.67 - */ - function readSync( - fd: number, - buffer: 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. - */ - function readSync( - fd: number, - buffer: ArrayBufferView, - opts?: ReadSyncOptions, - ): number; - /** - * Asynchronously reads the entire contents of a file. - * - * ```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.0.67 - * @param path filename or file descriptor - */ - function readFile( - path: PathOrFileDescriptor, - options: - | ({ - encoding?: null | undefined; - flag?: string | undefined; - } & Abortable) - | undefined - | null, - callback: (err: SystemError | 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. - * 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'`. - */ - function readFile( - path: PathOrFileDescriptor, - options: - | ({ - encoding: BufferEncoding; - flag?: string | undefined; - } & Abortable) - | BufferEncoding, - callback: (err: SystemError | null, data: string) => void, - ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile( - path: PathOrFileDescriptor, - options: - | (ObjectEncodingOptions & { - flag?: string | undefined; - } & Abortable) - | BufferEncoding - | undefined - | null, - callback: (err: SystemError | 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. - */ - function readFile( - path: PathOrFileDescriptor, - callback: (err: SystemError | null, data: Buffer) => void, - ): void; - // namespace readFile { - // /** - // * 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'`. - // */ - // 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. - // * 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'`. - // */ - // 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. - // * 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'`. - // */ - // function __promisify__( - // path: PathOrFileDescriptor, - // options?: - // | (ObjectEncodingOptions & { - // flag?: string | undefined; - // }) - // | BufferEncoding - // | null - // ): Promise; - // } - /** - * 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.0.67 - * @param path filename or file descriptor - */ - 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. - * 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'`. - */ - 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. - * 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'`. - */ - function readFileSync( - path: PathOrFileDescriptor, - options?: - | (ObjectEncodingOptions & { - flag?: string | undefined; - }) - | BufferEncoding - | null, - ): string | Buffer; - 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. - * - * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that - * performs multiple `write` calls internally to write the buffer passed to it. - * - * 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.0.67 - * @param file filename or file descriptor - */ - function writeFile( - file: PathOrFileDescriptor, - data: string | ArrayBufferView | ArrayBufferLike, - 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. - * 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. - */ - function writeFile( - path: PathOrFileDescriptor, - data: string | ArrayBufferView | ArrayBufferLike, - callback: NoParamCallback, - ): void; - // namespace writeFile { - // /** - // * 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. - // */ - // function __promisify__( - // path: PathOrFileDescriptor, - // data: string | ArrayBufferView, - // options?: WriteFileOptions - // ): Promise; - // } - /** - * 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.0.67 - * @param file filename or file descriptor - */ - function writeFileSync( - file: PathOrFileDescriptor, - data: string | ArrayBufferView | ArrayBufferLike, - 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.0.67 - * @param path filename or file descriptor - */ - 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. - * 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. - */ - function appendFile( - file: PathOrFileDescriptor, - data: string | Uint8Array, - callback: NoParamCallback, - ): void; - // namespace appendFile { - // /** - // * 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. - // */ - // function __promisify__( - // file: PathOrFileDescriptor, - // data: string | Uint8Array, - // options?: WriteFileOptions - // ): Promise; - // } - /** - * 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.0.67 - * @param path filename or file descriptor - */ - function appendFileSync( - path: PathOrFileDescriptor, - data: string | Uint8Array, - options?: WriteFileOptions, - ): void; - - /** - * 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.67 - */ - function exists(path: PathLike, callback: (exists: boolean) => void): void; - /** - * 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.0.67 - */ - function existsSync(path: PathLike): boolean; - namespace constants { - // File Access Constants - /** Constant for fs.access(). File is visible to the calling process. */ - var F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ - var R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ - var W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ - var X_OK: number; - // File Copy Constants - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - var 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. - */ - var 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. - */ - var COPYFILE_FICLONE_FORCE: number; - // File Open Constants - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - var O_RDONLY: number; - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - var O_WRONLY: number; - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - var O_RDWR: number; - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - var 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. */ - var 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). - */ - var 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. */ - var O_TRUNC: number; - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - var O_APPEND: number; - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - var O_DIRECTORY: number; - /** - * constant for fs.open(). - * Flag indicating reading accesses to the file system will no longer result in - * an update to the atime information associated with the file. - * This flag is available on Linux operating systems only. - */ - var O_NOATIME: number; - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - var O_NOFOLLOW: number; - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - var 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. */ - var O_DSYNC: number; - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - var O_SYMLINK: number; - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - var O_DIRECT: number; - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - var 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. */ - var S_IFMT: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - var S_IFREG: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - var S_IFDIR: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - var S_IFCHR: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - var S_IFBLK: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - var S_IFIFO: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - var S_IFLNK: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - var 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. */ - var S_IRWXU: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - var S_IRUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - var S_IWUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - var 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. */ - var S_IRWXG: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - var S_IRGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - var S_IWGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - var 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. */ - var S_IRWXO: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - var S_IROTH: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - var S_IWOTH: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - var 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, - * this flag is ignored. - */ - var UV_FS_O_FILEMAP: number; - } - /** - * 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.0.67 - * @param [mode=fs.constants.F_OK] - */ - 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. - */ - function access(path: PathLike, callback: NoParamCallback): void; - // namespace access { - // /** - // * 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_. - // */ - // function __promisify__(path: PathLike, mode?: number): Promise; - // } - /** - * 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.0.67 - * @param [mode=fs.constants.F_OK] - */ - function accessSync(path: PathLike, mode?: number): void; - - interface StreamOptions { - flags?: string | undefined; - encoding?: BufferEncoding | undefined; - fd?: number | undefined; // | promises.FileHandle; - mode?: number | undefined; - autoClose?: boolean | undefined; - /** - * @default false - */ - emitClose?: boolean | undefined; - start?: number | undefined; - highWaterMark?: number | undefined; - } - interface ReadStreamOptions extends StreamOptions { - end?: number | undefined; - } - /** - * 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 createReadStream( - path: PathLike, - options?: BufferEncoding | ReadStreamOptions, - ): 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` 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.0.67 - */ - /** - * 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?: ErrnoException | null) => void): Promise; - /** - * 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: string | symbol, - listener: (...args: any[]) => void, - ): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "ready", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "ready", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - // prependListener(event: 'close', listener: () => void): this; - // prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; - // prependListener(event: 'end', listener: () => void): this; - // prependListener(event: 'error', listener: (err: Error) => void): this; - // prependListener(event: 'open', listener: (fd: number) => void): this; - // prependListener(event: 'pause', listener: () => void): this; - // prependListener(event: 'readable', listener: () => void): this; - // prependListener(event: 'ready', listener: () => void): this; - // prependListener(event: 'resume', listener: () => void): this; - // prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - // prependOnceListener(event: 'close', listener: () => void): this; - // prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; - // prependOnceListener(event: 'end', listener: () => void): this; - // prependOnceListener(event: 'error', listener: (err: Error) => void): this; - // prependOnceListener(event: 'open', listener: (fd: number) => void): this; - // prependOnceListener(event: 'pause', listener: () => void): this; - // prependOnceListener(event: 'readable', listener: () => void): this; - // prependOnceListener(event: 'ready', listener: () => void): this; - // prependOnceListener(event: 'resume', listener: () => void): this; - // prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * * 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?: ErrnoException | null) => void): Promise; - /** - * 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; - } - // function fdatasync(fd: number, callback: NoParamCallback): void; - // namespace fdatasync { - // /** - // * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - // * @param fd A file descriptor. - // */ - // function __promisify__(fd: number): Promise; - // } - /** - * 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.0.67 - */ - // 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. - * - * `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 v0.0.67 - * @param src source filename to copy - * @param dest destination filename of the copy operation - * @param [mode=0] modifiers for copy operation. - */ - function copyFile( - src: PathLike, - dest: PathLike, - callback: NoParamCallback, - ): void; - function copyFile( - src: PathLike, - dest: PathLike, - mode: number, - callback: NoParamCallback, - ): void; - // namespace copyFile { - // function __promisify__( - // src: PathLike, - // dst: PathLike, - // mode?: number - // ): Promise; - // } - /** - * 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 v0.0.67 - * @param src source filename to copy - * @param dest destination filename of the copy operation - * @param [mode=0] modifiers for copy operation. - */ - function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; - /** - * 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. - * - * - * 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.67 - */ - function writev( - fd: number, - buffers: ReadonlyArray, - cb: ( - err: SystemError | null, - bytesWritten: number, - buffers: ArrayBufferView[], - ) => void, - ): void; - function writev( - fd: number, - buffers: ReadonlyArray, - position: number, - cb: ( - err: SystemError | null, - bytesWritten: number, - buffers: ArrayBufferView[], - ) => void, - ): void; - interface WriteVResult { - bytesWritten: number; - buffers: ArrayBufferView[]; - } - // namespace writev { - // function __promisify__( - // fd: number, - // buffers: ReadonlyArray, - // position?: number - // ): Promise; - // } - /** - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link writev}. - * @since v0.0.67 - * @return The number of bytes written. - */ - function writevSync( - fd: number, - buffers: ReadonlyArray, - position?: number, - ): number; - /** - * 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 v0.0.67 - */ - function readv( - fd: number, - buffers: ReadonlyArray, - cb: ( - err: SystemError | null, - bytesRead: number, - buffers: ArrayBufferView[], - ) => void, - ): void; - function readv( - fd: number, - buffers: ReadonlyArray, - position: number, - cb: ( - err: SystemError | null, - bytesRead: number, - buffers: ArrayBufferView[], - ) => void, - ): void; - interface ReadVResult { - bytesRead: number; - buffers: ArrayBufferView[]; - } - // namespace readv { - // function __promisify__( - // fd: number, - // buffers: ReadonlyArray, - // position?: number - // ): Promise; - // } - /** - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link readv}. - * @since v0.0.67 - * @return The number of bytes read. - */ - function readvSync( - fd: number, - buffers: ReadonlyArray, - position?: number, - ): number; - interface OpenDirOptions { - encoding?: BufferEncoding | undefined; - /** - * Number of directory entries that are buffered - * internally when reading from the directory. Higher values lead to better - * performance but higher memory usage. - * @default 32 - */ - bufferSize?: number | undefined; - } - - interface BigIntStats extends StatsBase { - atimeNs: bigint; - mtimeNs: bigint; - ctimeNs: bigint; - birthtimeNs: bigint; - } - interface BigIntOptions { - bigint: true; - } - interface StatOptions { - bigint?: boolean | undefined; - } - interface StatSyncOptions extends StatOptions { - throwIfNoEntry?: boolean | undefined; - } - interface CopyOptions { - /** - * Dereference symlinks - * @default false - */ - dereference?: boolean; - /** - * When `force` is `false`, and the destination - * exists, throw an error. - * @default false - */ - errorOnExist?: boolean; - /** - * function to filter copied files/directories. Return - * `true` to copy the item, `false` to ignore it. - */ - filter?(source: string, destination: string): 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; - } - /** - * Class: fs.StatWatcher - * Extends `EventEmitter` - * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. - */ - export interface StatWatcher extends EventEmitter { - /** - * 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; - /** - * 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.6.8 - */ - close(): void; - - /** - * When called, requests that the Node.js event loop not exit so long as the is active. Calling watcher.ref() multiple times will have no effect. - */ - ref(): void; - - /** - * When called, the active 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 object's callback is invoked. Calling watcher.unref() multiple times will have no effect. - */ - unref(): 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; - 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; - 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; - 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; - 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; - } - - type WatchOptions = { - encoding?: BufferEncoding; - persistent?: boolean; - recursive?: boolean; - signal?: AbortSignal; - }; - export type WatchEventType = "rename" | "change" | "error" | "close"; - type WatchListener = ( - event: WatchEventType, - filename: T | Error | undefined, - ) => 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.6.8 - * @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. - * @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?: 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. - * @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: 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. - */ - export function watch( - filename: PathLike, - listener?: WatchListener, - ): FSWatcher; - /** - * 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 interface WatchFileOptions { - bigint?: boolean | undefined; - persistent?: boolean | undefined; - interval?: number | undefined; - } - export type StatsListener = (current: Stats, previous: Stats) => void; - export type BigIntStatsListener = ( - current: BigIntStats, - previous: BigIntStats, - ) => void; - /** - * 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 'node: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 - */ - export function watchFile( - filename: PathLike, - options: - | (WatchFileOptions & { - bigint?: false | undefined; - }) - | undefined, - listener: StatsListener, - ): StatWatcher; - export function watchFile( - filename: PathLike, - options: - | (WatchFileOptions & { - bigint: true; - }) - | undefined, - listener: BigIntStatsListener, - ): 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. - */ - export function watchFile( - filename: PathLike, - listener: StatsListener, - ): StatWatcher; - /** - * 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?: StatsListener, - ): void; - export function unwatchFile( - filename: PathLike, - listener?: BigIntStatsListener, - ): void; - 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; - /** - * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} - */ - mode?: number; - /** - * When `true` timestamps from `source` will - * be preserved. - * @default false - */ - preserveTimestamps?: boolean; - /** - * Copy directories recursively. - * @default false - */ - recursive?: boolean; - /** - * When true, path resolution for symlinks will be skipped - * @default false - */ - verbatimSymlinks?: 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/`. - * - * @param source source path to copy. - * @param destination destination path to copy to. - */ - export function cp( - source: string | URL, - destination: string | URL, - callback: (error: ErrnoException | null) => void, - ): void; - export function cp( - source: string | URL, - destination: string | URL, - options: CopyOptions, - callback: (error: 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/`. - * - * @param source source path to copy. - * @param destination destination path to copy to. - */ - export function cpSync( - source: string | URL, - destination: string | URL, - options?: CopySyncOptions, - ): void; -} - -declare module "node:fs" { - export * from "fs"; -} diff --git a/packages/bun-types/fs/promises.d.ts b/packages/bun-types/fs/promises.d.ts deleted file mode 100644 index 7c409fcba1..0000000000 --- a/packages/bun-types/fs/promises.d.ts +++ /dev/null @@ -1,807 +0,0 @@ -/** - * The `fs/promises` API provides asynchronous file system methods that return - * promises. - * - * The promise APIs use the underlying Bun 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. - */ -declare module "fs/promises" { - import { ArrayBufferView } from "bun"; - import type { - Stats, - BigIntStats, - StatOptions, - MakeDirectoryOptions, - Dirent, - ObjectEncodingOptions, - OpenMode, - Mode, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - CopyOptions, - EncodingOption, - WriteFileOptions, - SimlinkType, - Abortable, - RmOptions, - RmDirOptions, - WatchOptions, - WatchEventType, - } from "node:fs"; - - const constants: typeof import("node:fs")["constants"]; - - 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; - } - /** - * Tests a user"s permissions for the file or directory specified by `path`. - * The `mode` argument is an optional integer that specifies the accessibility - * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` - * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for - * possible values of `mode`. - * - * If the accessibility check is successful, the promise is resolved with no - * value. If any of the accessibility checks fail, the promise is rejected - * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and - * written by the current process. - * - * ```js - * import { access } 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 v0.0.67 - * @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. - * - * 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 v0.0.67 - * @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, - mode?: number, - ): Promise; - /** - * 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 v0.0.67 - * @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?: OpenMode, mode?: Mode): Promise; - /** - * Renames `oldPath` to `newPath`. - * @since v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function rename(oldPath: PathLike, newPath: PathLike): Promise; - /** - * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. - * @since v0.0.67 - * @param [len=0] - * @return Fulfills with `undefined` upon success. - */ - function truncate(path: PathLike, len?: number): Promise; - /** - * 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 v0.0.67 - * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. - */ - 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; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir( - path: PathLike, - options?: Mode | MakeDirectoryOptions | null | undefined, - ): 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 v0.0.67 - * @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; - recursive?: boolean | undefined; - }) - | BufferEncoding - | undefined - | 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: - | { - encoding: "buffer"; - withFileTypes?: false | undefined; - recursive?: boolean | 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?: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | 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: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - ): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with the `linkString` upon success. - */ - function readlink( - path: PathLike, - options?: EncodingOption | 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?: EncodingOption | string | null, - ): Promise; - /** - * 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 v0.0.67 - * @param [type="file"] - * @return Fulfills with `undefined` upon success. - */ - function symlink( - target: PathLike, - path: PathLike, - type?: SimlinkType, - ): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. - */ - function lstat( - path: PathLike, - options?: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - ): Promise; - function lstat( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - ): Promise; - function lstat( - path: PathLike, - options?: StatOptions, - ): Promise; - /** - * @since v0.0.67 - * @return Fulfills with the {fs.Stats} object for the given `path`. - */ - function stat( - path: PathLike, - options?: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - ): Promise; - function stat( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - ): Promise; - function stat( - path: PathLike, - options?: StatOptions, - ): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function unlink(path: PathLike): Promise; - /** - * Changes the permissions of a file. - * @since v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function chmod(path: PathLike, mode: Mode): Promise; - /** - * Changes the permissions on a symbolic link. - * - * This method is only implemented on macOS. - * @deprecated Since v0.4.7 - * @return Fulfills with `undefined` upon success. - */ - function lchmod(path: PathLike, mode: Mode): Promise; - /** - * Changes the ownership on a symbolic link. - * @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. - * @since v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function lutimes( - path: PathLike, - atime: TimeLike, - mtime: TimeLike, - ): Promise; - /** - * Changes the ownership of a file. - * @since v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function chown(path: PathLike, uid: number, gid: number): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with `undefined` upon success. - */ - function utimes( - path: PathLike, - atime: TimeLike, - mtime: TimeLike, - ): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with the resolved path upon success. - */ - function realpath( - path: PathLike, - options?: EncodingOption | 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?: EncodingOption | null, - ): Promise; - /** - * 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 v0.0.67 - * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. - */ - function mkdtemp( - prefix: string, - options?: EncodingOption | 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?: EncodingOption | null, - ): Promise; - /** - * 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. - * - * The `encoding` option is ignored if `data` is a buffer. - * - * If `options` is a string, then it specifies the encoding. - * - * The `mode` option only affects the newly created file. See `fs.open()` for more details. - * - * Any specified `FileHandle` has to support writing. - * - * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file - * without waiting for the promise to be settled. - * - * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience - * method that performs multiple `write` calls internally to write the buffer - * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. - * - * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. - * Cancelation is "best effort", and some amount of data is likely still - * to be written. - * - * ```js - * import { writeFile } from "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 v0.0.67 - * @param file filename or `FileHandle` - * @return Fulfills with `undefined` upon success. - */ - function writeFile( - file: PathOrFileDescriptor, - data: string | ArrayBufferView | ArrayBufferLike, - options?: WriteFileOptions, - ): Promise; - /** - * 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 v0.0.67 - * @param path filename or {FileHandle} - * @return Fulfills with `undefined` upon success. - */ - function appendFile( - path: PathOrFileDescriptor, - data: string | Uint8Array, - options?: WriteFileOptions, - ): 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 v0.0.67 - * @param path filename or `FileHandle` - * @return Fulfills with the contents of the file. - */ - function readFile( - path: PathOrFileDescriptor, - options?: - | ({ - encoding?: null | undefined; - flag?: string | 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. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `"r"`. - */ - function readFile( - path: PathOrFileDescriptor, - 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. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `"r"`. - */ - function readFile( - path: PathOrFileDescriptor, - options?: - | (ObjectEncodingOptions & - Abortable & { - flag?: OpenMode | undefined; - }) - | BufferEncoding - | null, - ): Promise; - /** - * 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, options?: RmOptions): Promise; - - /** - * Asynchronously test whether or not the given path exists by checking with the file system. - * - * ```ts - * import { exists } from 'fs/promises'; - * - * const e = await exists('/etc/passwd'); - * e; // boolean - * ``` - */ - function exists(path: PathLike): Promise; - - /** - * @deprecated Use `fs.promises.rm()` instead. - * - * Asynchronously remove a directory. - * - * ```ts - * import { rmdir } from 'fs/promises'; - * - * // remove a directory - * await rmdir('/tmp/mydir'); // Promise - * ``` - * - * To remove a directory recursively, use `fs.promises.rm()` instead, with the `recursive` option set to `true`. - */ - function rmdir(path: PathLike, options?: RmDirOptions): Promise; - - interface FileChangeInfo { - eventType: WatchEventType; - filename: T; - } - /** - * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. - * - * ```js - * const { watch } = require('node:fs/promises'); - * - * const ac = new AbortController(); - * const { signal } = ac; - * setTimeout(() => ac.abort(), 10000); - * - * (async () => { - * try { - * const watcher = watch(__filename, { signal }); - * for await (const event of watcher) - * console.log(event); - * } catch (err) { - * if (err.name === 'AbortError') - * return; - * throw err; - * } - * })(); - * ``` - * - * On most platforms, `'rename'` is emitted whenever a filename appears or - * disappears in the directory. - * - * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. - * @since v0.6.8 - * @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 `source` to `destination`, - * including subdirectories and files. - * - * When copying a directory to another directory, globs are not supported and - * behavior is similar to `cp dir1/ dir2/`. - * - * @param source source path to copy. - * @param destination destination path to copy to. - * @return Fulfills with `undefined` upon success. - */ - function cp( - source: string | URL, - destination: string | URL, - options?: CopyOptions, - ): Promise; -} - -declare module "node:fs/promises" { - export * from "fs/promises"; -} diff --git a/packages/bun-types/globals.d.ts b/packages/bun-types/globals.d.ts index 4e722fb513..4469903e51 100644 --- a/packages/bun-types/globals.d.ts +++ b/packages/bun-types/globals.d.ts @@ -1,108 +1,163 @@ -/** - * "blob" is not supported yet +/* + * @types/node uses the existence of `onmessage` to detect if lib.dom.d.ts is loaded + * and defers to the DOM types if it is. Declaring onmessage here lets us override the + * definitions in @types/node by the same mechanism. the following global vars/interfaces + * MUST be declared in Bun's types, or they will be ill-defined/empty. + * + * - Blob + * - Event + * - EventTarget + * - RequestInit + * - Request + * - ResponseInit + * - Response + * - FormData + * - Headers + * - File + * - performance + * - URL + * - URLSearchParams + * - TextDecoder + * - TextEncoder + * - BroadcastChannel + * - MessageChannel + * - MessagePort */ -type BinaryType = "nodebuffer" | "arraybuffer" | "blob"; -type Transferable = ArrayBuffer | MessagePort; -type MessageEventSource = undefined; -type Encoding = "utf-8" | "windows-1252" | "utf-16"; -type Platform = - | "aix" - | "android" - | "darwin" - | "freebsd" - | "haiku" - | "linux" - | "openbsd" - | "sunos" - | "win32" - | "cygwin" - | "netbsd"; -type Architecture = - | "arm" - | "arm64" - | "ia32" - | "mips" - | "mipsel" - | "ppc" - | "ppc64" - | "s390" - | "s390x" - | "x64"; -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"; +declare var onmessage: typeof globalThis extends { + onerror: any; + onmessage: infer T; +} + ? T + : any; + +declare namespace Bun { + type _ReadableStreamDefaultReader = typeof globalThis extends { + onerror: any; + ReadableStreamDefaultReader: infer T; + } + ? T + : import("stream/web").ReadableStreamDefaultReader; + type _ReadableStreamDefaultController = typeof globalThis extends { + onerror: any; + ReadableStreamDefaultController: infer T; + } + ? T + : import("stream/web").ReadableStreamDefaultController; +} +declare namespace Bun { + type _ReadableStream = typeof globalThis extends { + onerror: any; + ReadableStream: infer T; + } + ? T + : import("stream/web").ReadableStream; + type _WritableStream = typeof globalThis extends { + onerror: any; + WritableStream: infer T; + } + ? T + : import("stream/web").WritableStream; +} +interface ReadableStream extends Bun._ReadableStream {} +declare var ReadableStream: typeof globalThis extends { + onerror: any; + ReadableStream: infer T; +} + ? T + : { + prototype: ReadableStream; + new ( + underlyingSource?: Bun.UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; + new ( + underlyingSource?: Bun.DirectUnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream; + }; + +interface WritableStream extends Bun._WritableStream {} +declare var WritableStream: typeof globalThis extends { + onerror: any; + WritableStream: infer T; +} + ? T + : { + prototype: WritableStream; + new ( + underlyingSink?: Bun.UnderlyingSink, + strategy?: QueuingStrategy, + ): WritableStream; + }; + +declare namespace Bun { + type Transferable = ArrayBuffer | MessagePort; + type MessageEventSource = undefined; + type Encoding = "utf-8" | "windows-1252" | "utf-16"; + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "s390" + | "s390x" + | "x64"; + 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 UncaughtExceptionListener = ( + error: Error, + origin: UncaughtExceptionOrigin, + ) => 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 that the value is an Error. + */ + type UnhandledRejectionListener = ( + reason: unknown, + promise: Promise, + ) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: NodeJS.Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type BlobPart = string | Blob | BufferSource; + type TimerHandler = (...args: any[]) => void; + type BufferSource = NodeJS.TypedArray | DataView | ArrayBufferLike; + type DOMHighResTimeStamp = number; + type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +} interface ArrayConstructor { fromAsync( asyncItems: AsyncIterable | Iterable | ArrayLike, mapfn?: (value: any, index: number) => any, thisArg?: any, - ): Promise>; + ): Promise; } -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 UncaughtExceptionListener = ( - error: Error, - origin: UncaughtExceptionOrigin, -) => 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 that the value is an Error. - */ -type UnhandledRejectionListener = ( - reason: unknown, - promise: Promise, -) => void; -type WarningListener = (warning: Error) => void; -type MessageListener = (message: unknown, sendHandle: unknown) => void; -type SignalsListener = (signal: Signals) => void; -type MultipleResolveListener = ( - type: MultipleResolveType, - promise: Promise, - value: unknown, -) => void; -// type WorkerListener = (worker: Worker) => void; - interface ConsoleOptions { stdout: import("stream").Writable; stderr?: import("stream").Writable; @@ -210,76 +265,22 @@ interface Console { timeStamp(label?: string): void; trace(...data: any[]): void; warn(...data: any[]): void; -} -declare var console: Console & { /** * Creates a new Console with one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr. */ - Console: { - new (options: ConsoleOptions): Console; - new ( - stdout: import("stream").Writable, - stderr?: import("stream").Writable, - ignoreErrors?: boolean, - ): Console; - }; -}; - -declare namespace NodeJS { - interface RequireResolve { - (id: string, options?: { paths?: string[] | undefined }): string; - paths(request: string): string[] | null; - } - - interface Require { - (id: string): any; - resolve: RequireResolve; - cache: Record; - main: NodeModule | undefined; - } - - interface ProcessEnv {} - 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"; + // Console: { + // new (options: ConsoleOptions): Console; + // new ( + // stdout: import("stream").Writable, + // stderr?: import("stream").Writable, + // ignoreErrors?: boolean, + // ): Console; + // }; } +declare var console: Console; + interface ImportMeta { /** * `file://` url string for the current module. @@ -290,7 +291,7 @@ interface ImportMeta { * "file:///Users/me/projects/my-app/src/my-app.ts" * ``` */ - readonly url: string; + url: string; /** * Absolute path to the source file */ @@ -312,7 +313,7 @@ interface ImportMeta { * import.meta.env === process.env * ``` */ - readonly env: import("bun").Env; + readonly env: NodeJS.ProcessEnv; /** * Resolve a module ID the same as if you imported it * @@ -383,11 +384,11 @@ declare var __filename: string; /** @deprecated Please use `import.meta.dir` instead. */ declare var __dirname: string; - -interface StructuredSerializeOptions { - transfer?: Transferable[]; +declare namespace Bun { + interface StructuredSerializeOptions { + transfer?: Bun.Transferable[]; + } } - /** * Creates a deep clone of an object. * @@ -395,410 +396,219 @@ interface StructuredSerializeOptions { */ declare function structuredClone( value: T, - options?: StructuredSerializeOptions, + options?: Bun.StructuredSerializeOptions, ): T; -declare var MessagePort: typeof import("worker_threads").MessagePort; -declare type MessagePort = import("worker_threads").MessagePort; -declare var MessageChannel: typeof import("worker_threads").MessageChannel; -declare type MessageChannel = import("worker_threads").MessageChannel; -declare var BroadcastChannel: typeof import("worker_threads").BroadcastChannel; -declare type BroadcastChannel = import("worker_threads").BroadcastChannel; +// -interface AbstractWorkerEventMap { - error: ErrorEvent; -} +declare namespace Bun { + interface AbstractWorkerEventMap { + error: ErrorEvent; + } -interface WorkerEventMap extends AbstractWorkerEventMap { - message: MessageEvent; - messageerror: MessageEvent; - close: CloseEvent; - open: Event; -} + interface WorkerEventMap extends AbstractWorkerEventMap { + message: MessageEvent; + messageerror: MessageEvent; + close: CloseEvent; + open: Event; + } -interface AbstractWorker { - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorker/error_event) */ - onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; - addEventListener( - type: K, - listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, - options?: boolean | AddEventListenerOptions, - ): void; - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions, - ): void; - removeEventListener( - type: K, - listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, - options?: boolean | EventListenerOptions, - ): void; - removeEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions, - ): void; -} + type WorkerType = "classic" | "module"; + type RequestCredentials = import("undici-types").RequestCredentials; -/** - * Bun's Web Worker constructor supports some extra options on top of the API browsers have. - */ -interface WorkerOptions { - /** - * A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of - * the worker, which is mainly useful for debugging purposes. - */ - name?: string; + interface AbstractWorker { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorker/error_event) */ + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + addEventListener( + type: K, + listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; + } /** - * Use less memory, but make the worker slower. - * - * Internally, this sets the heap size configuration in JavaScriptCore to be - * the small heap instead of the large heap. + * Bun's Web Worker constructor supports some extra options on top of the API browsers have. */ - smol?: boolean; - - /** - * When `true`, the worker will keep the parent thread alive until the worker is terminated or `unref`'d. - * When `false`, the worker will not keep the parent thread alive. - * - * By default, this is `false`. - */ - ref?: boolean; - - /** - * In Bun, this does nothing. - */ - type?: string; - - /** - * List of arguments which would be stringified and appended to - * `Bun.argv` / `process.argv` in the worker. This is mostly similar to the `data` - * but the values will be available on the global `Bun.argv` as if they - * were passed as CLI options to the script. - */ - // argv?: any[] | undefined; - - /** If `true` and the first argument is a string, interpret the first argument to the constructor as a script that is executed once the worker is online. */ - // eval?: boolean | undefined; - - /** - * If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env. - */ - env?: - | Record - | typeof import("node:worker_threads")["SHARE_ENV"] - | undefined; - - /** - * In Bun, this does nothing. - */ - credentials?: string; - - /** - * @default true - */ - // trackUnmanagedFds?: boolean; - - // resourceLimits?: import("worker_threads").ResourceLimits; -} - -interface Worker extends EventTarget, AbstractWorker { - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/message_event) */ - onmessage: ((this: Worker, ev: MessageEvent) => any) | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/messageerror_event) */ - onmessageerror: ((this: Worker, ev: MessageEvent) => any) | null; - /** - * Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/postMessage) - */ - postMessage(message: any, transfer: Transferable[]): void; - postMessage(message: any, options?: StructuredSerializeOptions): void; - /** - * Aborts worker's associated global environment. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/terminate) - */ - terminate(): void; - addEventListener( - type: K, - listener: (this: Worker, ev: WorkerEventMap[K]) => any, - options?: boolean | AddEventListenerOptions, - ): void; - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions, - ): void; - removeEventListener( - type: K, - listener: (this: Worker, ev: WorkerEventMap[K]) => any, - options?: boolean | EventListenerOptions, - ): void; - removeEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions, - ): void; - - /** - * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default - * behavior). If the worker is `ref()`ed, calling `ref()` again has - * no effect. - * @since v10.5.0 - */ - ref(): void; - /** - * Calling `unref()` on a worker allows the thread to exit if this is the only - * active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect. - * @since v10.5.0 - */ - unref(): void; - - /** - * An integer identifier for the referenced thread. Inside the worker thread, - * it is available as `require('node:worker_threads').threadId`. - * This value is unique for each `Worker` instance inside a single process. - * @since v10.5.0 - */ - threadId: number; -} - -declare var Worker: { - prototype: Worker; - new (scriptURL: string | URL, options?: WorkerOptions): Worker; - /** - * This is the cloned value of the `data` property passed to `new Worker()` - * - * This is Bun's equivalent of `workerData` in Node.js. - */ - data: any; -}; - -interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; -} - -interface Process { - /** - * A Node.js LTS version - * - * To see the current Bun version, use {@link Bun.version} - */ - version: string; - /** - * Run a function on the next tick of the event loop - * - * This is the same as {@link queueMicrotask} - * - * @param callback - The function to run - */ - nextTick(callback: (...args: any) => any, ...args: any): void; - title: string; - exitCode: number; - browser: boolean; - versions: Record; - ppid: number; - hrtime: { - (time?: [number, number]): [number, number]; - bigint(): bigint; - }; - pid: number; - arch: Architecture; - platform: Platform; - argv: string[]; - execArgv: string[]; - env: import("bun").Env; - allowedNodeEnvironmentFlags: Set; - debugPort: number; - - /** Whether you are using Bun */ - isBun: 1; // FIXME: this should actually return a boolean - /** The current git sha of Bun **/ - revision: string; - chdir(directory: string): void; - cwd(): string; - exit(code?: number): never; - reallyExit(code?: number): never; - getgid(): number; - // setgid(id: number | string): void; - getuid(): number; - // setuid(id: number | string): void; - geteuid: () => number; - // seteuid: (id: number | string) => void; - getegid: () => number; - // setegid: (id: number | string) => void; - getgroups: () => number[]; - // setgroups?: (groups: ReadonlyArray) => void; - dlopen(module: { exports: any }, filename: string, flags?: number): void; - stdin: import("tty").ReadStream; - stdout: import("tty").WriteStream; - stderr: import("tty").WriteStream; - - /** - * - * @deprecated This is deprecated; use the "node:assert" module instead. - */ - assert(value: unknown, message?: string | Error): asserts value; - - /** - * exit the process with a fatal exception, sending SIGABRT - */ - abort(): never; - - /** - * Resolved absolute file path to the current Bun executable that is running - */ - readonly execPath: string; - /** - * The original argv[0] passed to Bun - */ - readonly argv0: string; - - /** - * Number of seconds the process has been running - * - * This uses a high-resolution timer, but divides from nanoseconds to seconds - * so there may be some loss of precision. - * - * For a more precise value, use `performance.timeOrigin` and `performance.now()` instead. - */ - uptime(): number; - - /** - * Bun process's file mode creation mask. - * - * @returns Bun process's file mode creation mask. - */ - umask(mask?: number): number; - - emitWarning(warning: string | Error /*name?: string, ctor?: Function*/): void; - - readonly config: Object; - - memoryUsage: { - (delta?: MemoryUsageObject): MemoryUsageObject; - - rss(): number; - }; - - cpuUsage(previousValue?: CPUUsageObject): CPUUsageObject; - - /** - * Does nothing in Bun - */ - setSourceMapsEnabled(enabled: boolean): void; - - kill(pid: number, signal?: string | number): true; - - 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: "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: Signals, listener: SignalsListener): this; - // once(event: "multipleResolves", listener: MultipleResolveListener): this; - // once(event: "worker", listener: WorkerListener): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - /** - * Returns the number of listeners listening for the event named `eventName`. - * If `listener` is provided, it will return how many times the listener is found - * in the list of the listeners of the event. - * @since v3.2.0 - * @param eventName The name of the event being listened for - * @param listener The event handler function - */ - listenerCount(eventName: string | symbol, listener?: Function): number; - - /** - * Get the constrained memory size for the process. - * - * On Linux, this is the memory limit for the process, accounting for cgroups 1 and 2. - * On other operating systems, this returns `undefined`. - */ - constrainedMemory(): number | undefined; - - send(data: any): void; - - report: { - getReport(): Object; + interface WorkerOptions { /** - * @TODO This is not implemented yet + * A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of + * the worker, which is mainly useful for debugging purposes. */ - writeReport(fileName?: string): void; - }; + name?: string; + + /** + * Use less memory, but make the worker slower. + * + * Internally, this sets the heap size configuration in JavaScriptCore to be + * the small heap instead of the large heap. + */ + smol?: boolean; + + /** + * When `true`, the worker will keep the parent thread alive until the worker is terminated or `unref`'d. + * When `false`, the worker will not keep the parent thread alive. + * + * By default, this is `false`. + */ + ref?: boolean; + + /** + * In Bun, this does nothing. + */ + type?: Bun.WorkerType | undefined; + + /** + * List of arguments which would be stringified and appended to + * `Bun.argv` / `process.argv` in the worker. This is mostly similar to the `data` + * but the values will be available on the global `Bun.argv` as if they + * were passed as CLI options to the script. + */ + // argv?: any[] | undefined; + + /** If `true` and the first argument is a string, interpret the first argument to the constructor as a script that is executed once the worker is online. */ + // eval?: boolean | undefined; + + /** + * If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env. + */ + env?: + | Record + | typeof import("node:worker_threads")["SHARE_ENV"] + | undefined; + + /** + * In Bun, this does nothing. + */ + credentials?: Bun.RequestCredentials | undefined; + + /** + * @default true + */ + // trackUnmanagedFds?: boolean; + + // resourceLimits?: import("worker_threads").ResourceLimits; + } + + interface Worker extends EventTarget, AbstractWorker { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/message_event) */ + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/messageerror_event) */ + onmessageerror: ((this: Worker, ev: MessageEvent) => any) | null; + /** + * Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/postMessage) + */ + postMessage(message: any, transfer: Transferable[]): void; + postMessage(message: any, options?: StructuredSerializeOptions): void; + /** + * Aborts worker's associated global environment. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/terminate) + */ + terminate(): void; + addEventListener( + type: K, + listener: (this: Worker, ev: WorkerEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: Worker, ev: WorkerEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; + + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default + * behavior). If the worker is `ref()`ed, calling `ref()` again has + * no effect. + * @since v10.5.0 + */ + ref(): void; + /** + * Calling `unref()` on a worker allows the thread to exit if this is the only + * active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect. + * @since v10.5.0 + */ + unref(): void; + + /** + * An integer identifier for the referenced thread. Inside the worker thread, + * it is available as `require('node:worker_threads').threadId`. + * This value is unique for each `Worker` instance inside a single process. + * @since v10.5.0 + */ + threadId: number; + } } -interface MemoryUsageObject { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; +declare namespace Bun { + type _Worker = typeof globalThis extends { onerror: any; Worker: infer T } + ? T + : Bun.Worker; } - -interface CPUUsageObject { - user: number; - system: number; +interface Worker extends Bun._Worker {} +declare var Worker: typeof globalThis extends { + onerror: any; + Worker: infer T; } + ? T + : { + prototype: Worker; + new ( + scriptURL: string | URL, + options?: Bun.WorkerOptions | undefined, + ): Worker; + /** + * This is the cloned value of the `data` property passed to `new Worker()` + * + * This is Bun's equivalent of `workerData` in Node.js. + */ + data: any; + }; -declare var process: Process; +declare namespace NodeJS { + interface Process { + readonly version: string; + browser: boolean; -declare module "process" { - var process: Process; - export = process; -} -declare module "node:process" { - import process = require("process"); - export = process; -} + /** Whether you are using Bun */ + isBun: 1; // FIXME: this should actually return a boolean + /** The current git sha of Bun **/ + revision: string; + reallyExit(code?: number): never; + dlopen(module: { exports: any }, filename: string, flags?: number): void; -interface BlobInterface { - text(): Promise; - arrayBuffer(): Promise; - json(): Promise; - formData(): Promise; -} - -type BlobPart = string | Blob | BufferSource; -interface BlobPropertyBag { - /** Set a default "type". Not yet implemented. */ - type?: string; - /** Not implemented in Bun yet. */ - // endings?: "transparent" | "native"; + /** + * @deprecated This is deprecated; use the "node:assert" module instead. + */ + assert(value: unknown, message?: string | Error): asserts value; + } } /** @@ -813,534 +623,151 @@ interface BlobPropertyBag { * In all methods of this interface, header names are matched by * case-insensitive byte sequence. */ + +//// interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; - entries(): IterableIterator<[string, string]>; - keys(): IterableIterator; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[string, string]>; - forEach( - callbackfn: (value: string, key: string, parent: Headers) => void, - thisArg?: any, - ): void; - - /** - * Convert {@link Headers} to a plain JavaScript object. - * - * About 10x faster than `Object.fromEntries(headers.entries())` - * - * Called when you run `JSON.stringify(headers)` - * - * Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is. - */ + // /** + // * Convert {@link Headers} to a plain JavaScript object. + // * + // * About 10x faster than `Object.fromEntries(headers.entries())` + // * + // * Called when you run `JSON.stringify(headers)` + // * + // * Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is. + // */ toJSON(): Record; - - /** - * Get the total number of headers - */ + // /** + // * Get the total number of headers + // */ readonly count: number; - - /** - * Get all headers matching the name - * - * Only supports `"Set-Cookie"`. All other headers are empty arrays. - * - * @param name - The header name to get - * - * @returns An array of header values - * - * @example - * ```ts - * const headers = new Headers(); - * headers.append("Set-Cookie", "foo=bar"); - * headers.append("Set-Cookie", "baz=qux"); - * headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"] - * ``` - */ + // /** + // * Get all headers matching the name + // * + // * Only supports `"Set-Cookie"`. All other headers are empty arrays. + // * + // * @param name - The header name to get + // * + // * @returns An array of header values + // * + // * @example + // * ```ts + // * const headers = new Headers(); + // * headers.append("Set-Cookie", "foo=bar"); + // * headers.append("Set-Cookie", "baz=qux"); + // * headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"] + // * ``` + // */ getAll(name: "set-cookie" | "Set-Cookie"): string[]; } -declare var Headers: { - prototype: Headers; - new (init?: HeadersInit): Headers; -}; - -type HeadersInit = - | Headers - | Record - | Array<[string, string]> - | IterableIterator<[string, string]>; -type ResponseType = - | "basic" - | "cors" - | "default" - | "error" - | "opaque" - | "opaqueredirect"; - -type FormDataEntryValue = File | string; +declare namespace Bun { + type HeadersInit = + | Headers + | Record + | Array<[string, string]> + | IterableIterator<[string, string]>; + type ResponseType = + | "basic" + | "cors" + | "default" + | "error" + | "opaque" + | "opaqueredirect"; + type FormDataEntryValue = File | string; +} /** Provides a way to easily construct a set of key/value pairs representing * form fields and their values, which can then be easily sent using the * XMLHttpRequest.send() method. It uses the same format a form would use if the * encoding type were set to "multipart/form-data". */ -interface FormData { - /** - * Appends a new value onto an existing key inside a FormData object, or adds - * the key if it does not already exist. - * - * @param name The name of the field whose data is contained in value. - * @param value The field's value. - * @param fileName The filename reported to the server. - * - * ## Upload a file - * ```ts - * const formData = new FormData(); - * formData.append("username", "abc123"); - * formData.append("avatar", Bun.file("avatar.png"), "avatar.png"); - * await fetch("https://example.com", { method: "POST", body: formData }); - * ``` - */ - append(name: string, value: string | Blob, fileName?: string): void; - delete(name: string): void; - get(name: string): FormDataEntryValue | null; - getAll(name: string): FormDataEntryValue[]; - has(name: string): boolean; - set(name: string, value: string | Blob, fileName?: string): void; - keys(): IterableIterator; - values(): IterableIterator; - entries(): IterableIterator<[string, FormDataEntryValue]>; - [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>; - forEach( - callback: (value: FormDataEntryValue, key: string, parent: this) => void, - thisArg?: any, - ): void; -} - -declare var FormData: { - prototype: FormData; - new (): FormData; -}; - -declare interface Blob { - /** - * Create a new view **without 🚫 copying** the underlying data. - * - * Similar to [`BufferSource.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BufferSource/subarray) - * - * @param begin The index that sets the beginning of the view. - * @param end The index that sets the end of the view. - * - */ - slice(begin?: number, end?: number, contentType?: string): Blob; - - /** - * Create a new view **without 🚫 copying** the underlying data. - * - * Similar to [`BufferSource.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BufferSource/subarray) - * - * @param begin The index that sets the beginning of the view. - * @param end The index that sets the end of the view. - * - */ - slice(begin?: number, contentType?: string): Blob; - - /** - * Create a new view **without 🚫 copying** the underlying data. - * - * Similar to [`BufferSource.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BufferSource/subarray) - * - * @param begin The index that sets the beginning of the view. - * @param end The index that sets the end of the view. - * - */ - slice(contentType?: string): Blob; - - /** - * Read the data from the blob as a string. It will be decoded from UTF-8. - */ - text(): Promise; - - /** - * Read the data from the blob as a ReadableStream. - */ - stream(chunkSize?: number): ReadableStream; - - /** - * Read the data from the blob as an ArrayBuffer. - * - * This copies the data into a new ArrayBuffer. - */ - arrayBuffer(): Promise; - - /** - * Read the data from the blob as a JSON object. - * - * This first decodes the data from UTF-8, then parses it as JSON. - * - */ - json(): Promise; - - /** - * Read the data from the blob as a {@link FormData} object. - * - * This first decodes the data from UTF-8, then parses it as a - * `multipart/form-data` body or a `application/x-www-form-urlencoded` body. - * - * The `type` property of the blob is used to determine the format of the - * body. - * - * This is a non-standard addition to the `Blob` API, to make it conform more - * closely to the `BodyMixin` API. - */ - formData(): Promise; - - type: string; - readonly size: number; -} -declare var Blob: { - prototype: Blob; - /** - * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - * - * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects - * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - */ - new (parts?: BlobPart[], options?: BlobPropertyBag): Blob; -}; interface File extends Blob { readonly lastModified: number; readonly name: string; } -declare var File: { - prototype: File; +declare var File: typeof globalThis extends { onerror: any; File: infer T } + ? T + : { + prototype: File; - /** - * Create a new [File](https://developer.mozilla.org/en-US/docs/Web/API/File) - * - * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects - * @param `name` - The name of the file - * @param `options` - An object containing properties to be added to the [File](https://developer.mozilla.org/en-US/docs/Web/API/File) - */ - new ( - parts: BlobPart[], - name: string, - options?: BlobPropertyBag & { lastModified?: Date | number }, - ): File; -}; + /** + * Create a new [File](https://developer.mozilla.org/en-US/docs/Web/API/File) + * + * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects + * @param `name` - The name of the file + * @param `options` - An object containing properties to be added to the [File](https://developer.mozilla.org/en-US/docs/Web/API/File) + */ + new ( + parts: Bun.BlobPart[], + name: string, + options?: BlobPropertyBag & { lastModified?: Date | number }, + ): File; + }; -interface ResponseInit { - headers?: HeadersInit; - /** @default 200 */ - status?: number | bigint; +declare namespace Bun { + interface ResponseInit { + headers?: HeadersInit; + /** @default 200 */ + status?: number; - /** @default "OK" */ - statusText?: string; + /** @default "OK" */ + statusText?: string; + } } -/** - * Represents an HTTP [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) - * - * Use it to get the body of the response, the status code, and other information. - * - * @example - * ```ts - * const response: Response = await fetch("https://remix.run"); - * await response.text(); - * ``` - * @example - * ```ts - * const response: Response = await fetch("https://remix.run"); - * await Bun.write("remix.html", response); - * ``` - */ -declare class Response implements BlobInterface { - constructor( - body?: - | ReadableStream - | BlobPart - | BlobPart[] - | FormData - | URLSearchParams - | null, - options?: ResponseInit, - ); +declare namespace Bun { + // type RequestCache = "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload"; + // type RequestCredentials = "include" | "omit" | "same-origin"; + // type RequestDestination = + // | "" + // | "audio" + // | "audioworklet" + // | "document" + // | "embed" + // | "font" + // | "frame" + // | "iframe" + // | "image" + // | "manifest" + // | "object" + // | "paintworklet" + // | "report" + // | "script" + // | "sharedworker" + // | "style" + // | "track" + // | "video" + // | "worker" + // | "xslt"; + // type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin"; + // type RequestRedirect = "error" | "follow" | "manual"; + // type ReferrerPolicy = + // | "" + // | "no-referrer" + // | "no-referrer-when-downgrade" + // | "origin" + // | "origin-when-cross-origin" + // | "same-origin" + // | "strict-origin" + // | "strict-origin-when-cross-origin" + // | "unsafe-url"; + // type RequestInfo = Request | string | RequestInit; - /** - * Create a new {@link Response} with a JSON body - * - * @param body - The body of the response - * @param options - options to pass to the response - * - * @example - * - * ```ts - * const response = Response.json({hi: "there"}); - * console.assert( - * await response.text(), - * `{"hi":"there"}` - * ); - * ``` - * ------- - * - * This is syntactic sugar for: - * ```js - * new Response(JSON.stringify(body), {headers: { "Content-Type": "application/json" }}) - * ``` - * @link https://github.com/whatwg/fetch/issues/1389 - */ - static json(body?: any, options?: ResponseInit | number): Response; - /** - * Create a new {@link Response} that redirects to url - * - * @param url - the URL to redirect to - * @param status - the HTTP status code to use for the redirect - */ - // tslint:disable-next-line:unified-signatures - static redirect(url: string, status?: number): Response; - - /** - * Create a new {@link Response} that redirects to url - * - * @param url - the URL to redirect to - * @param options - options to pass to the response - */ - // tslint:disable-next-line:unified-signatures - static redirect(url: string, options?: ResponseInit): Response; - - /** - * Create a new {@link Response} that has a network error - */ - static error(): Response; - - /** - * HTTP [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) sent with the response. - * - * @example - * ```ts - * const {headers} = await fetch("https://remix.run"); - * headers.get("Content-Type"); - * headers.get("Content-Length"); - * headers.get("Set-Cookie"); - * ``` - */ - readonly headers: Headers; - - /** - * HTTP response body as a [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) - * - * This is part of web Streams - * - * @example - * ```ts - * const {body} = await fetch("https://remix.run"); - * const reader = body.getReader(); - * const {done, value} = await reader.read(); - * console.log(value); // Uint8Array - * ``` - */ - readonly body: ReadableStream | null; - - /** - * Has the body of the response already been consumed? - */ - readonly bodyUsed: boolean; - - /** - * Read the data from the Response as a string. It will be decoded from UTF-8. - * - * When the body is valid latin1, this operation is zero copy. - */ - text(): Promise; - - /** - * Read the data from the Response as a string. It will be decoded from UTF-8. - * - * When the body is valid latin1, this operation is zero copy. - */ - arrayBuffer(): Promise; - - /** - * Read the data from the Response as a JSON object. - * - * This first decodes the data from UTF-8, then parses it as JSON. - * - */ - json(): Promise; - - /** - * Read the data from the Response as a Blob. - * - * This allows you to reuse the underlying data. - * - * @returns Promise - The body of the response as a {@link Blob}. - */ - blob(): Promise; - - /** - * Read the data from the Response as a {@link FormData} object. - * - * This first decodes the data from UTF-8, then parses it as a - * `multipart/form-data` body or a `application/x-www-form-urlencoded` body. - * - * If no `Content-Type` header is present, the promise will be rejected. - * - * @returns Promise - The body of the response as a {@link FormData}. - */ - formData(): Promise; - - readonly ok: boolean; - readonly redirected: boolean; - /** - * HTTP status code - * - * @example - * 200 - * - * 0 for network errors - */ - readonly status: number; - readonly statusText: string; - readonly type: ResponseType; - /** HTTP url as a string */ - readonly url: string; - - /** Copy the Response object into a new Response, including the body */ - clone(): Response; -} - -type RequestCache = - | "default" - | "force-cache" - | "no-cache" - | "no-store" - | "only-if-cached" - | "reload"; -type RequestCredentials = "include" | "omit" | "same-origin"; -type RequestDestination = - | "" - | "audio" - | "audioworklet" - | "document" - | "embed" - | "font" - | "frame" - | "iframe" - | "image" - | "manifest" - | "object" - | "paintworklet" - | "report" - | "script" - | "sharedworker" - | "style" - | "track" - | "video" - | "worker" - | "xslt"; -type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin"; -type RequestRedirect = "error" | "follow" | "manual"; -type ReferrerPolicy = - | "" - | "no-referrer" - | "no-referrer-when-downgrade" - | "origin" - | "origin-when-cross-origin" - | "same-origin" - | "strict-origin" - | "strict-origin-when-cross-origin" - | "unsafe-url"; -// type RequestInfo = Request | string | RequestInit; - -type BodyInit = ReadableStream | XMLHttpRequestBodyInit | URLSearchParams; -type XMLHttpRequestBodyInit = Blob | BufferSource | string | FormData; -type ReadableStreamController = ReadableStreamDefaultController; -type ReadableStreamDefaultReadResult = - | ReadableStreamDefaultReadValueResult - | ReadableStreamDefaultReadDoneResult; -interface ReadableStreamDefaultReadManyResult { - done: boolean; - /** Number of bytes */ - size: number; - value: T[]; -} -type ReadableStreamReader = ReadableStreamDefaultReader; - -interface RequestInit { - /** - * A BodyInit object or null to set request's body. - */ - body?: BodyInit | null; - /** - * A string indicating how the request will interact with the browser's cache to set request's cache. - * - * Note: as of Bun v0.5.7, this is not implemented yet. - */ - cache?: RequestCache; - /** - * A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. - */ - credentials?: RequestCredentials; - /** - * A Headers object, an object literal, or an array of two-item arrays to set request's headers. - */ - headers?: HeadersInit; - /** - * A cryptographic hash of the resource to be fetched by request. Sets request's integrity. - * - * Note: as of Bun v0.5.7, this is not implemented yet. - */ - integrity?: string; - /** - * A boolean to set request's keepalive. - * - * Available in Bun v0.2.0 and above. - * - * This is enabled by default - */ - keepalive?: boolean; - /** - * A string to set request's method. - */ - method?: string; - /** - * A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. - */ - mode?: RequestMode; - /** - * A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. - */ - redirect?: RequestRedirect; - /** - * A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. - */ - referrer?: string; - /** - * A referrer policy to set request's referrerPolicy. - */ - referrerPolicy?: ReferrerPolicy; - /** - * An AbortSignal to set request's signal. - */ - signal?: AbortSignal | null; - /** - * Can only be null. Used to disassociate request from any Window. - * - * This does nothing in Bun - */ - window?: any; - - /** - * Enable or disable HTTP request timeout - */ - timeout?: boolean; + type BodyInit = ReadableStream | XMLHttpRequestBodyInit | URLSearchParams; + type XMLHttpRequestBodyInit = Blob | BufferSource | string | FormData; + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + interface ReadableStreamDefaultReadManyResult { + done: boolean; + /** Number of bytes */ + size: number; + value: T[]; + } + type ReadableStreamReader = ReadableStreamDefaultReader; } interface FetchRequestInit extends RequestInit { @@ -1362,208 +789,53 @@ interface FetchRequestInit extends RequestInit { */ tls?: { rejectUnauthorized?: boolean | undefined; // Defaults to true - checkServerIdentity?: any | undefined; // TODO: change `any` to `checkServerIdentity` + checkServerIdentity?: any; // TODO: change `any` to `checkServerIdentity` }; } -/** - * [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) represents an HTTP request. - * - * @example - * ```ts - * const request = new Request("https://remix.run/"); - * await fetch(request); - * ``` - * - * @example - * ```ts - * const request = new Request("https://remix.run/"); - * await fetch(request); - * ``` - */ -declare class Request implements BlobInterface { - // Request | string | RequestInit; - constructor(requestInfo: string, requestInit?: RequestInit); - constructor(requestInfo: RequestInit & { url: string }); - constructor(requestInfo: Request, requestInit?: RequestInit); +declare namespace Bun { + type _WebSocket = typeof globalThis extends { + onerror: any; + WebSocket: infer T; + } + ? T + : import("ws").WebSocket; +} +interface WebSocket extends Bun._WebSocket {} +declare var WebSocket: typeof globalThis extends { + onerror: any; + WebSocket: infer T; +} + ? T + : typeof import("ws"); - /** - * Read or write the HTTP headers for this request. - * - * @example - * ```ts - * const request = new Request("https://remix.run/"); - * request.headers.set("Content-Type", "application/json"); - * request.headers.set("Accept", "application/json"); - * await fetch(request); - * ``` - */ - headers: Headers; - - /** - * The URL (as a string) corresponding to the HTTP request - * @example - * ```ts - * const request = new Request("https://remix.run/"); - * request.url; // "https://remix.run/" - * ``` - */ - readonly url: string; - - /** - * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a string. It will be decoded from UTF-8. - * - * When the body is valid latin1, this operation is zero copy. - */ - text(): Promise; - - /** - * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a {@link ReadableStream}. - * - * Streaming **outgoing** HTTP request bodies via `fetch()` is not yet supported in - * Bun. - * - * Reading **incoming** HTTP request bodies via `ReadableStream` in `Bun.serve()` is supported - * as of Bun v0.2.0. - * - * - */ - get body(): ReadableStream | null; - - /** - * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as an ArrayBuffer. - * - */ - arrayBuffer(): Promise; - - /** - * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a JSON object. - * - * This first decodes the data from UTF-8, then parses it as JSON. - * - */ - json(): Promise; - - /** - * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a `Blob`. - * - * This allows you to reuse the underlying data. - * - */ - blob(): Promise; - - /** - * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. - */ - readonly cache: RequestCache; - /** - * Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. - */ - readonly credentials: RequestCredentials; - /** - * Returns the kind of resource requested by request, e.g., "document" or "script". - * - * In Bun, this always returns "navigate". - */ - readonly destination: RequestDestination; - /** - * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] - * - * This does nothing in Bun right now. - */ - readonly integrity: string; - /** - * Returns a boolean indicating whether or not request can outlive the global in which it was created. - * - * In Bun, this always returns false. - */ - readonly keepalive: boolean; - /** - * Returns request's HTTP method, which is "GET" by default. - */ - readonly method: string; - /** - * Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs. - */ - readonly mode: RequestMode; - /** - * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. - */ - readonly redirect: RequestRedirect; - /** - * Returns the referrer of request. Its value can be a same-origin URL - * if explicitly set in init, the empty string to indicate no referrer, - * and "about:client" when defaulting to the global's default. This is - * used during fetching to determine the value of the `Referer` header - * of the request being made. - */ - readonly referrer: string; - /** - * Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer. - */ - readonly referrerPolicy: ReferrerPolicy; - /** - * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. - */ - readonly signal: AbortSignal; - - /** Copy the Request object into a new Request, including the body */ - clone(): Request; - - /** - * Read the body from the Request as a {@link FormData} object. - * - * This first decodes the data from UTF-8, then parses it as a - * `multipart/form-data` body or a `application/x-www-form-urlencoded` body. - * - * @returns Promise - The body of the request as a {@link FormData}. - */ - formData(): Promise; - - /** - * Has the body of the request been read? - * - * [Request.bodyUsed](https://developer.mozilla.org/en-US/docs/Web/API/Request/bodyUsed) - */ - readonly bodyUsed: boolean; +declare namespace Bun { + type _Crypto = typeof globalThis extends { + onerror: any; + Crypto: infer T; + } + ? T + : import("crypto").webcrypto.Crypto; } -declare interface Crypto { - readonly subtle: SubtleCrypto; +interface Crypto extends Bun._Crypto {} - getRandomValues(array: T): T; - /** - * Generate a cryptographically secure random UUID. - * - * @example - * - * ```js - * crypto.randomUUID() - * '5e6adf82-f516-4468-b1e1-33d6f664d7dc' - * ``` - */ - randomUUID(): string; +declare var Crypto: typeof globalThis extends { + onerror: any; + Crypto: infer T; } -declare var Crypto: { - prototype: Crypto; - new (): Crypto; -}; + ? T + : { + prototype: Crypto; + new (): Crypto; + }; -declare var crypto: Crypto; - -/** - * [`atob`](https://developer.mozilla.org/en-US/docs/Web/API/atob) decodes base64 into ascii text. - * - * @param asciiText The base64 string to decode. - */ -declare function atob(encodedData: string): string; - -/** - * [`btoa`](https://developer.mozilla.org/en-US/docs/Web/API/btoa) encodes ascii text into base64. - * - * @param stringToEncode The ascii text to encode. - */ -declare function btoa(stringToEncode: string): string; +declare var crypto: typeof globalThis extends { + onerror: any; + crypto: infer T; +} + ? T + : Crypto; /** * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All @@ -1573,85 +845,76 @@ declare function btoa(stringToEncode: string): string; * const encoder = new TextEncoder(); * const uint8array = encoder.encode('this is some data'); * ``` - * */ -declare class TextEncoder { - /** - * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. - */ - readonly encoding: "utf-8"; +declare namespace Bun { + type NodeTextEncoder = import("util").TextEncoder; + interface TextEncoder extends NodeTextEncoder { + /** + * 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?: Bun.BufferSource, + ): import("util").EncodeIntoResult; + } - constructor(encoding?: "utf-8"); - - /** - * 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; - /** - * 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?: BufferSource): EncodeIntoResult; + type _TextEncoder = typeof globalThis extends { + onerror: any; + TextEncoder: infer T; + } + ? T + : TextEncoder; + type _TextDecoder = typeof globalThis extends { + onerror: any; + TextDecoder: infer T; + } + ? T + : import("util").TextDecoder; } -/** - * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. - * - * ```js - * const decoder = new TextDecoder(); - * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); - * console.log(decoder.decode(u8arr)); // Hello - * ``` - */ -declare 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?: Encoding, - options?: { fatal?: boolean; ignoreBOM?: boolean }, - ); - - /** - * 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 `BufferSource` instance containing the encoded data. - */ - decode(input?: BufferSource | ArrayBuffer): string; +interface TextEncoder extends Bun._TextEncoder {} +declare var TextEncoder: typeof globalThis extends { + onerror: any; + TextEncoder: infer T; } + ? T + : { + prototype: TextEncoder; + new ( + encoding?: Bun.Encoding, + options?: { fatal?: boolean; ignoreBOM?: boolean }, + ): TextEncoder; + }; + +interface TextDecoder extends Bun._TextDecoder {} +declare var TextDecoder: typeof globalThis extends { + onerror: any; + TextDecoder: infer T; +} + ? T + : { + prototype: TextDecoder; + new ( + encoding?: Bun.Encoding, + options?: { fatal?: boolean; ignoreBOM?: boolean }, + ): TextDecoder; + }; /** * ShadowRealms are a distinct global environment, with its own global object * containing its own intrinsics and built-ins (standard objects that are not * bound to global variables, like the initial value of Object.prototype). * - * * @example * * ```js @@ -1686,7 +949,7 @@ declare class TextDecoder { * console.assert(result === 16); // yields true * ``` */ -declare class ShadowRealm { +interface ShadowRealm { /** * Creates a new [ShadowRealm](https://github.com/tc39/proposal-shadowrealm/blob/main/explainer.md#introduction) * @@ -1724,51 +987,30 @@ declare class ShadowRealm { * console.assert(result === 16); // yields true * ``` */ - constructor(); importValue(specifier: string, bindingName: string): Promise; evaluate(sourceText: string): any; } -declare var performance: { - /** - * Milliseconds since Bun.js started - * - * Uses a high-precision system timer to measure the time elapsed since the - * Bun.js runtime was initialized. The value is represented as a double - * precision floating point number. The value is monotonically increasing - * during the lifetime of the runtime. - * - */ - now: () => number; - - /** - * The timeOrigin read-only property of the Performance interface returns the - * high resolution timestamp that is used as the baseline for - * performance-related timestamps. - * - * @link https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin - */ - readonly timeOrigin: number; +declare var ShadowRealm: { + prototype: ShadowRealm; + new (): ShadowRealm; }; -/** - * Cancel a repeating timer by its timer ID. - * @param id timer id - */ -declare function clearInterval(id?: number | Timer): void; -/** - * Cancel a delayed function call by its timer ID. - * @param id timer id - */ -declare function clearTimeout(id?: number | Timer): void; -/** - * Cancel an immediate function call by its immediate ID. - * @param id immediate id - */ -declare function clearImmediate(id?: number | Timer): void; -// declare function createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; -// declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; +declare namespace Bun { + type _Performance = typeof globalThis extends { + onerror: any; + } + ? {} + : import("perf_hooks").Performance; +} +interface Performance extends Bun._Performance {} +declare var performance: typeof globalThis extends { + onerror: any; + performance: infer T; +} + ? T + : Performance; /** * Send a HTTP(s) request * @@ -1776,9 +1018,8 @@ declare function clearImmediate(id?: number | Timer): void; * @param init A structured value that contains settings for the fetch() request. * * @returns A promise that resolves to {@link Response} object. - * - * */ + // tslint:disable-next-line:unified-signatures declare function fetch(request: Request, init?: RequestInit): Promise; /** @@ -1788,8 +1029,6 @@ declare function fetch(request: Request, init?: RequestInit): Promise; * @param init A structured value that contains settings for the fetch() request. * * @returns A promise that resolves to {@link Response} object. - * - * */ declare function fetch( url: string | URL | Request, @@ -1811,12 +1050,27 @@ interface Timer { [Symbol.toPrimitive](): number; } +/** + * Cancel a repeating timer by its timer ID. + * @param id timer id + */ +declare function clearInterval(id?: number | Timer): void; +/** + * Cancel a delayed function call by its timer ID. + * @param id timer id + */ +declare function clearTimeout(id?: number | Timer): void; +/** + * Cancel an immediate function call by its immediate ID. + * @param id immediate id + */ +declare function clearImmediate(id?: number | Timer): void; /** * Run a function immediately after main event loop is vacant * @param handler function to call */ declare function setImmediate( - handler: TimerHandler, + handler: Bun.TimerHandler, ...arguments: any[] ): Timer; /** @@ -1825,7 +1079,7 @@ declare function setImmediate( * @param interval milliseconds to wait between calls */ declare function setInterval( - handler: TimerHandler, + handler: Bun.TimerHandler, interval?: number, ...arguments: any[] ): Timer; @@ -1835,10 +1089,142 @@ declare function setInterval( * @param timeout milliseconds to wait between calls */ declare function setTimeout( - handler: TimerHandler, + handler: Bun.TimerHandler, timeout?: number, ...arguments: any[] ): Timer; + +declare namespace Bun { + type _Event = typeof globalThis extends { onerror: any; Event: any } + ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + + // See comment above explaining conditional type + type _EventTarget = typeof globalThis extends { + onerror: any; + EventTarget: any; + } + ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + + interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + } + + interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; + } + + interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; + signal?: AbortSignal; + } + + interface EventListener { + (evt: Event): void; + } + + interface EventListenerObject { + handleEvent(object: Event): void; + } + + interface FetchEvent extends Event { + readonly request: Request; + readonly url: string; + + waitUntil(promise: Promise): void; + respondWith(response: Response | Promise): void; + } + + interface EventMap { + fetch: FetchEvent; + message: MessageEvent; + messageerror: MessageEvent; + // exit: Event; + } +} + +interface Event extends Bun._Event {} +declare var Event: typeof globalThis extends { onerror: any; Event: infer T } + ? T + : { + prototype: Event; + new (type: string, eventInitDict?: Bun.EventInit): Event; + }; +interface EventTarget extends Bun._EventTarget {} +declare var EventTarget: typeof globalThis extends { + onerror: any; + EventTarget: infer T; +} + ? T + : { + prototype: EventTarget; + new (): EventTarget; + }; declare function addEventListener( type: K, listener: (this: object, ev: EventMap[K]) => any, @@ -1846,255 +1232,87 @@ declare function addEventListener( ): void; declare function addEventListener( type: string, - listener: EventListenerOrEventListenerObject, + listener: Bun.EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions, ): void; declare function removeEventListener( type: K, listener: (this: object, ev: EventMap[K]) => any, - options?: boolean | EventListenerOptions, + options?: boolean | Bun.EventListenerOptions, ): void; declare function removeEventListener( type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions, + listener: Bun.EventListenerOrEventListenerObject, + options?: boolean | Bun.EventListenerOptions, ): void; -// ----------------------- -// ----------------------- -// --- libdom.d.ts +declare namespace Bun { + interface ErrorEventInit extends EventInit { + colno?: number; + error?: any; + filename?: string; + lineno?: number; + message?: string; + } -interface ErrorEventInit extends EventInit { - colno?: number; - error?: any; - filename?: string; - lineno?: number; - message?: string; + interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; + } + + interface MessageEventInit extends EventInit { + data?: T; + lastEventId?: string; + origin?: string; + source?: Bun.MessageEventSource | null; + } + + interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + } + + interface EventListenerOptions { + capture?: boolean; + } + + interface CustomEventInit extends Bun.EventInit { + detail?: T; + } + + /** A message received by a target object. */ + interface MessageEvent extends Event { + /** Returns the data of the message. */ + readonly data: T; + /** Returns the last event ID string, for server-sent events. */ + readonly lastEventId: string; + /** Returns the origin of the message, for server-sent events and cross-document messaging. */ + readonly origin: string; + /** Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. */ + readonly ports: readonly MessagePort[]; // ReadonlyArray; + readonly source: Bun.MessageEventSource | null; + /** @deprecated */ + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: null, + ): void; + } + + type _MessageEvent = typeof globalThis extends { + onerror: any; + MessageEvent: infer T; + } + ? T + : MessageEvent; } -interface CloseEventInit extends EventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} - -interface MessageEventInit extends EventInit { - data?: T; - lastEventId?: string; - origin?: string; - source?: MessageEventSource; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} - -interface EventListenerOptions { - capture?: boolean; -} - -interface UIEventInit extends EventInit { - detail?: number; - view?: null; - /** @deprecated */ - which?: number; -} - -interface EventModifierInit extends UIEventInit { - altKey?: boolean; - ctrlKey?: boolean; - metaKey?: boolean; - modifierAltGraph?: boolean; - modifierCapsLock?: boolean; - modifierFn?: boolean; - modifierFnLock?: boolean; - modifierHyper?: boolean; - modifierNumLock?: boolean; - modifierScrollLock?: boolean; - modifierSuper?: boolean; - modifierSymbol?: boolean; - modifierSymbolLock?: boolean; - shiftKey?: boolean; -} - -interface EventSourceInit { - withCredentials?: boolean; -} - -/** 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. - */ - 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. - */ - abort(reason?: any): void; -} - -/** EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. */ -interface EventTarget { - /** - * Appends an event listener for events whose type attribute value is - * type. The callback argument sets the callback that will be invoked - * when the event is dispatched. - * - * The options argument sets listener-specific options. For - * compatibility this can be a boolean, in which case the method behaves - * exactly as if the value was specified as options's capture. - * - * When set to true, options's capture prevents callback from being - * invoked when the event's eventPhase attribute value is - * BUBBLING_PHASE. When false (or not present), callback will not be - * invoked when event's eventPhase attribute value is CAPTURING_PHASE. - * Either way,callback will be invoked if event's eventPhase attribute - * value is AT_TARGET. - * - * When set to true, options's passive indicates that the callback will - * not cancel the event by invoking preventDefault(). This is used to - * enable performance optimizations described in § 2.8 Observing event - * listeners. - * - * When set to true, options's once indicates that the callback will - * only be invoked once after which the event listener will be removed. - * - * If an AbortSignal is passed for options's signal, then the event - * listener will be removed when signal is aborted. - * - * The event listener is appended to target's event listener list and is - * not appended if it has the same type, callback, and capture. - */ - addEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: AddEventListenerOptions | boolean, - ): void; - /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ - dispatchEvent(event: Event): boolean; - /** Removes the event listener in target's event listener list with the same type, callback, and options. */ - removeEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean, - ): void; -} - -declare var EventTarget: { - prototype: EventTarget; - new (): EventTarget; -}; - -/** An event which takes place in the DOM. */ -interface Event { - /** - * Returns true or false depending on how event was initialized. True - * if event goes through its target's ancestors in reverse tree order, - * and false otherwise. - */ - readonly bubbles: boolean; - cancelBubble: boolean; - /** - * Returns true or false depending on how event was initialized. Its - * return value does not always carry meaning, but true can indicate - * that part of the operation during which event was dispatched, can be - * canceled by invoking the preventDefault() method. - */ - readonly cancelable: boolean; - /** - * Returns true or false depending on how event was initialized. True - * if event invokes listeners past a ShadowRoot node that is the root of - * its target, and false otherwise. - */ - readonly composed: boolean; - /** - * Returns the object whose event listener's callback is currently - * being invoked. - */ - readonly currentTarget: T | null; - /** - * Returns true if preventDefault() was invoked successfully to - * indicate cancelation, and false otherwise. - */ - readonly defaultPrevented: boolean; - /** - * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, - * AT_TARGET, and BUBBLING_PHASE. - */ - readonly eventPhase: number; - /** - * Returns true if event was dispatched by the user agent, and false - * otherwise. - */ - readonly isTrusted: boolean; - /** - * @deprecated - */ - returnValue: boolean; - /** - * @deprecated - */ - readonly srcElement: EventTarget | null; - /** - * Returns the object to which event is dispatched (its target). - */ - readonly target: EventTarget | null; - /** - * Returns the event's timestamp as the number of milliseconds measured - * relative to the time origin. - */ - readonly timeStamp: DOMHighResTimeStamp; - /** - * Returns the type of event, e.g. "click", "hashchange", or "submit". - */ - readonly type: string; - /** - * Returns the invocation target objects of event's path (objects on - * which listeners will be invoked), except for any nodes in shadow - * trees of which the shadow root's mode is "closed" that are not - * reachable from event's currentTarget. - */ - composedPath(): EventTarget[]; - /** - * @deprecated - */ - initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; - /** - * If invoked when the cancelable attribute value is true, and while - * executing a listener for the event with passive set to false, signals - * to the operation that caused event to be dispatched that it needs to - * be canceled. - */ - preventDefault(): void; - /** - * Invoking this method prevents event from reaching any registered - * event listeners after the current one finishes running and, when - * dispatched in a tree, also prevents event from reaching any other - * objects. - */ - stopImmediatePropagation(): void; - /** - * When dispatched in a tree, invoking this method prevents event from - * reaching any objects other than the current object. - */ - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; -} - -declare var Event: { - prototype: Event; - new (type: string, eventInitDict?: EventInit): Event; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; -}; - /** * Events providing information related to errors in scripts or in files. */ @@ -2108,7 +1326,7 @@ interface ErrorEvent extends Event { declare var ErrorEvent: { prototype: ErrorEvent; - new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent; + new (type: string, eventInitDict?: Bun.ErrorEventInit): ErrorEvent; }; /** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */ @@ -2123,40 +1341,22 @@ interface CloseEvent extends Event { declare var CloseEvent: { prototype: CloseEvent; - new (type: string, eventInitDict?: CloseEventInit): CloseEvent; + new (type: string, eventInitDict?: Bun.CloseEventInit): CloseEvent; }; -/** A message received by a target object. */ -interface MessageEvent extends Event { - /** Returns the data of the message. */ - readonly data: T; - /** Returns the last event ID string, for server-sent events. */ - readonly lastEventId: string; - /** Returns the origin of the message, for server-sent events and cross-document messaging. */ - readonly origin: string; - /** Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. */ - readonly ports: ReadonlyArray; - readonly source: MessageEventSource; - /** @deprecated */ - initMessageEvent( - type: string, - bubbles?: boolean, - cancelable?: boolean, - data?: any, - origin?: string, - lastEventId?: string, - source?: null, - ): void; -} - -declare var MessageEvent: { - prototype: MessageEvent; - new (type: string, eventInitDict?: MessageEventInit): MessageEvent; -}; - -interface CustomEventInit extends EventInit { - detail?: T; +interface MessageEvent extends Bun._MessageEvent {} +declare var MessageEvent: typeof globalThis extends { + onerror: any; + MessageEvent: infer T; } + ? T + : { + prototype: MessageEvent; + new ( + type: string, + eventInitDict?: Bun.MessageEventInit, + ): MessageEvent; + }; interface CustomEvent extends Event { /** Returns any custom data event was created with. Typically used for synthetic events. */ @@ -2172,352 +1372,67 @@ interface CustomEvent extends Event { declare var CustomEvent: { prototype: CustomEvent; - new (type: string, eventInitDict?: CustomEventInit): CustomEvent; + new (type: string, eventInitDict?: Bun.CustomEventInit): CustomEvent; }; -/** - * A map of WebSocket event names to event types. - */ -type WebSocketEventMap = { - open: Event; - message: MessageEvent; - close: CloseEvent; - ping: MessageEvent; - pong: MessageEvent; - error: Event; -}; - -/** - * A state that represents if a WebSocket is connected. - * - * - `WebSocket.CONNECTING` is `0`, the connection is pending. - * - `WebSocket.OPEN` is `1`, the connection is established and `send()` is possible. - * - `WebSocket.CLOSING` is `2`, the connection is closing. - * - `WebSocket.CLOSED` is `3`, the connection is closed or couldn't be opened. - * - * @link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState - */ -type WebSocketReadyState = 0 | 1 | 2 | 3; - -/** - * A client that makes an outgoing WebSocket connection. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket - * @example - * const ws = new WebSocket("wss://ws.postman-echo.com/raw"); - * - * ws.addEventListener("open", () => { - * console.log("Connected"); - * }); - * ws.addEventListener("message", ({ data }) => { - * console.log("Received:", data); // string or Buffer - * }); - * ws.addEventListener("close", ({ code, reason }) => { - * console.log("Disconnected:", code, reason); - * }); - */ -interface WebSocket extends EventTarget { - /** - * Sends a message. - * - * @param data the string, ArrayBuffer, or ArrayBufferView to send - * @example - * let ws: WebSocket; - * ws.send("Hello!"); - * ws.send(new TextEncoder().encode("Hello?")); - */ - send(data: string | BufferSource): void; - - /** - * Closes the connection. - * - * Here is a list of close codes: - * - `1000` means "normal closure" **(default)** - * - `1001` means the client is "going away" - * - `1009` means a message was too big and was rejected - * - `1011` means the server encountered an error - * - `1012` means the server is restarting - * - `1013` means the server is too busy or the client is rate-limited - * - `4000` through `4999` are reserved for applications (you can use it!) - * - * To abruptly close the connection without a code, use `terminate()` instead. - * - * @param code the close code - * @param reason the close reason - * @example - * let ws: WebSocket; - * ws.close(1013, "Exceeded the rate limit of 100 messages per minute."); - */ - close(code?: number, reason?: string): void; - - /** - * Closes the connection, abruptly. - * - * To gracefuly close the connection, use `close()` instead. - */ - terminate(): void; - - /** - * Sends a ping. - * - * @param data the string, ArrayBuffer, or ArrayBufferView to send - */ - ping(data?: string | BufferSource): void; - - /** - * Sends a pong. - * - * @param data the string, ArrayBuffer, or ArrayBufferView to send - */ - pong(data?: string | BufferSource): void; - - /** - * Sets how binary data is returned in events. - * - * - if `nodebuffer`, binary data is returned as `Buffer` objects. **(default)** - * - if `arraybuffer`, binary data is returned as `ArrayBuffer` objects. - * - if `blob`, binary data is returned as `Blob` objects. **(not supported)** - * - * In browsers, the default is `blob`, however in Bun, the default is `nodebuffer`. - * - * @example - * let ws: WebSocket; - * ws.binaryType = "arraybuffer"; - * ws.addEventListener("message", ({ data }) => { - * console.log(data instanceof ArrayBuffer); // true - * }); - */ - binaryType: BinaryType; - - /** - * The ready state of the connection. - * - * - `WebSocket.CONNECTING` is `0`, the connection is pending. - * - `WebSocket.OPEN` is `1`, the connection is established and `send()` is possible. - * - `WebSocket.CLOSING` is `2`, the connection is closing. - * - `WebSocket.CLOSED` is `3`, the connection is closed or couldn't be opened. - */ - readonly readyState: WebSocketReadyState; - - /** - * The resolved URL that established the connection. - */ - readonly url: string; - - /** - * The number of bytes that are queued, but not yet sent. - * - * When the connection is closed, the value is not reset to zero. - */ - readonly bufferedAmount: number; - - /** - * The protocol selected by the server, if any, otherwise empty. - */ - readonly protocol: string; - - /** - * The extensions selected by the server, if any, otherwise empty. - */ - readonly extensions: string; - - /** - * Sets the event handler for `open` events. - * - * If you need multiple event handlers, use `addEventListener("open")` instead. - */ - onopen: ((this: WebSocket, ev: Event) => unknown) | null; - - /** - * Sets the event handler for `close` events. - * - * If you need multiple event handlers, use `addEventListener("close")` instead. - */ - onclose: ((this: WebSocket, event: CloseEvent) => unknown) | null; - - /** - * Sets the event handler for `message` events. - * - * If you need multiple event handlers, use `addEventListener("message")` instead. - */ - onmessage: - | ((this: WebSocket, event: MessageEvent) => unknown) - | null; - - /** - * Sets the event handler for `error` events. - * - * If you need multiple event handlers, use `addEventListener("error")` instead. - */ - onerror: ((this: WebSocket, event: Event) => unknown) | null; - - addEventListener( - type: T, - listener: (this: WebSocket, event: WebSocketEventMap[T]) => unknown, - options?: boolean | AddEventListenerOptions, - ): void; - - addEventListener( - type: string, - listener: (this: WebSocket, event: Event) => unknown, - options?: boolean | AddEventListenerOptions, - ): void; - - removeEventListener( - type: T, - listener: (this: WebSocket, event: WebSocketEventMap[T]) => unknown, - options?: boolean | EventListenerOptions, - ): void; - - removeEventListener( - type: string, - listener: (this: WebSocket, event: Event) => unknown, - options?: boolean | EventListenerOptions, - ): void; +declare namespace Bun { + type _URL = typeof globalThis extends { onerror: any; URL: infer T } + ? T + : import("url").URL; } - -/** - * A client that makes an outgoing WebSocket connection. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket - * @example - * const ws = new WebSocket("wss://ws.postman-echo.com/raw"); - * - * ws.addEventListener("open", () => { - * console.log("Connected"); - * }); - * ws.addEventListener("message", ({ data }) => { - * console.log("Received:", data); // string or Buffer - * }); - * ws.addEventListener("close", ({ code, reason }) => { - * console.log("Disconnected:", code, reason); - * }); - */ -declare var WebSocket: { - prototype: WebSocket; - - new (url: string | URL, protocols?: string | string[]): WebSocket; - - new ( - url: string | URL, - options: { - /** - * Sets the headers when establishing a connection. - */ - headers?: HeadersInit; - /** - * Sets the sub-protocol the client is willing to accept. - */ - protocol?: string; - /** - * Sets the sub-protocols the client is willing to accept. - */ - protocols?: string[]; - /** - * Override the default TLS options - */ - tls?: { - rejectUnauthorized?: boolean | undefined; // Defaults to true - }; - }, - ): WebSocket; - - /** - * The connection is pending. - */ - readonly CONNECTING: 0; - - /** - * The connection is established and `send()` is possible. - */ - readonly OPEN: 1; - - /** - * The connection is closing. - */ - readonly CLOSING: 2; - - /** - * The connection is closed or couldn't be opened. - */ - readonly CLOSED: 3; -}; - /** * The URL interface represents an object providing static methods used for * creating object URLs. */ -interface URL { - hash: string; - host: string; - hostname: string; - href: string; - toString(): string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toJSON(): string; +interface URL extends Bun._URL {} +declare var URL: typeof globalThis extends { + onerror: any; + URL: infer T; } + ? T + : { + prototype: URL; + new (url: string | URL, base?: string | URL): URL; + /** Not implemented yet */ + createObjectURL(obj: Blob): string; + /** Not implemented yet */ + revokeObjectURL(url: string): void; -interface URLSearchParams { - /** Appends a specified key/value pair as a new search parameter. */ - append(name: string, value: string): void; - /** Deletes the given search parameter, and its associated value, from the list of all search parameters. */ - delete(name: string): void; - /** Returns the first value associated to the given search parameter. */ - get(name: string): string | null; - /** Returns all the values association with a given search parameter. */ - getAll(name: string): string[]; - /** Returns a Boolean indicating if such a search parameter exists. */ - has(name: string): boolean; - /** Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. */ - set(name: string, value: string): void; - sort(): void; - entries(): IterableIterator<[string, string]>; - /** Returns an iterator allowing to go through all keys of the key/value pairs of this search parameter. */ - keys(): IterableIterator; - /** Returns an iterator allowing to go through all values of the key/value pairs of this search parameter. */ - values(): IterableIterator; - forEach( - callbackfn: (value: string, key: string, parent: URLSearchParams) => void, - thisArg?: any, - ): void; - /** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ - toString(): string; - [Symbol.iterator](): IterableIterator<[string, string]>; + /** + * Check if `url` is a valid URL string + * + * @param url URL string to parse + * @param base URL to resolve against + */ + canParse(url: string, base?: string): boolean; + }; + +declare namespace Bun { + type _URLSearchParams = typeof globalThis extends { + onerror: any; + URL: infer T; + } + ? T + : import("url").URLSearchParams; } - -declare var URLSearchParams: { - prototype: URLSearchParams; - new ( - init?: string[][] | Record | string | URLSearchParams, - ): URLSearchParams; - toString(): string; -}; - -declare var URL: { - prototype: URL; - new (url: string | URL, base?: string | URL): URL; - /** Not implemented yet */ - createObjectURL(obj: Blob): string; - /** Not implemented yet */ - revokeObjectURL(url: string): void; - - /** - * Check if `url` is a valid URL string - * - * @param url URL string to parse - * @param base URL to resolve against - */ - canParse(url: string, base?: string): boolean; -}; - -type TimerHandler = (...args: any[]) => void; +interface URLSearchParams extends Bun._URLSearchParams {} +declare var URLSearchParams: typeof globalThis extends { + onerror: any; + URLSearchParams: infer T; +} + ? T + : { + prototype: URLSearchParams; + new ( + init?: + | string + | string[][] + | Record + | URLSearchParams + | undefined, + ): URLSearchParams; + toString(): string; + }; interface EventListener { (evt: Event): void; @@ -2527,11 +1442,6 @@ interface EventListenerObject { handleEvent(object: Event): void; } -declare var AbortController: { - prototype: AbortController; - new (): AbortController; -}; - interface FetchEvent extends Event { readonly request: Request; readonly url: string; @@ -2547,87 +1457,12 @@ interface EventMap { // exit: Event; } -interface AbortSignalEventMap { - abort: Event; -} - -interface AddEventListenerOptions extends EventListenerOptions { +interface AddEventListenerOptions extends Bun.EventListenerOptions { once?: boolean; passive?: boolean; signal?: AbortSignal; } -/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ -interface AbortSignal extends EventTarget { - /** - * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. - */ - readonly aborted: boolean; - - /** - * The reason the signal aborted, or undefined if not aborted. - */ - readonly reason: any; - - onabort: ((this: AbortSignal, ev: Event) => any) | null; - addEventListener( - type: K, - listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, - options?: boolean | AddEventListenerOptions, - ): void; - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions, - ): void; - removeEventListener( - type: K, - listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, - options?: boolean | EventListenerOptions, - ): void; - removeEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions, - ): void; -} - -declare var AbortSignal: { - prototype: AbortSignal; - new (): AbortSignal; - abort(reason?: any): AbortSignal; - /** - * Create an AbortSignal which times out after milliseconds - * - * @param milliseconds the number of milliseconds to delay until {@link AbortSignal.prototype.signal()} is called - * - * @example - * - * ## Timeout a `fetch()` request - * - * ```ts - * await fetch("https://example.com", { - * signal: AbortSignal.timeout(100) - * }) - * ``` - */ - timeout(milliseconds: number): AbortSignal; -}; - -// type AlgorithmIdentifier = Algorithm | string; -// type BodyInit = ReadableStream | XMLHttpRequestBodyInit; -type BufferSource = TypedArray | DataView | ArrayBufferLike; -// type COSEAlgorithmIdentifier = number; -// type CSSNumberish = number; -// type CanvasImageSource = -// | HTMLOrSVGImageElement -// | HTMLVideoElement -// | HTMLCanvasElement -// | ImageBitmap; -type DOMHighResTimeStamp = number; -// type EpochTimeStamp = number; -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; - /** * Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API) * @@ -2716,7 +1551,6 @@ declare var Loader: { * ``` * * @param specifier - module specifier as it appears in transpiled source code - * */ dependencyKeysIfEvaluated: (specifier: string) => string[]; /** @@ -2733,36 +1567,6 @@ declare var Loader: { resolve: (specifier: string, referrer: string) => string; }; -/** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */ -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]; - [Symbol.asyncIterator](): AsyncIterableIterator; - values(options?: { preventCancel: boolean }): AsyncIterableIterator; -} - -declare var ReadableStream: { - prototype: ReadableStream; - new ( - underlyingSource?: UnderlyingSource, - strategy?: QueuingStrategy, - ): ReadableStream; - new ( - underlyingSource?: DirectUnderlyingSource, - strategy?: QueuingStrategy, - ): ReadableStream; -}; - interface QueuingStrategy { highWaterMark?: number; size?: QueuingStrategySize; @@ -2778,9 +1582,15 @@ interface QueuingStrategyInit { } /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */ -interface ByteLengthQueuingStrategy extends QueuingStrategy { +// interface ByteLengthQueuingStrategy extends QueuingStrategy { +// readonly highWaterMark: number; +// readonly size: QueuingStrategySize; +// } +interface ByteLengthQueuingStrategy extends QueuingStrategy { readonly highWaterMark: number; - readonly size: QueuingStrategySize; + // changed from QueuingStrategySize + // to avoid conflict with lib.dom.d.ts + readonly size: QueuingStrategySize; } declare var ByteLengthQueuingStrategy: { @@ -2797,7 +1607,9 @@ interface ReadableStreamDefaultController { interface ReadableStreamDirectController { close(error?: Error): void; - write(data: BufferSource | ArrayBuffer | string): number | Promise; + write( + data: Bun.BufferSource | ArrayBuffer | string, + ): number | Promise; end(): number | Promise; flush(): number | Promise; start(): void; @@ -2810,14 +1622,14 @@ declare var ReadableStreamDefaultController: { interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { - read(): Promise>; + read(): Promise>; /** * Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time. - * Will only return a promise if the data is not immediatly available. + * Will only return a promise if the data is not immediately available. */ readMany(): - | Promise> - | ReadableStreamDefaultReadManyResult; + | Promise> + | Bun.ReadableStreamDefaultReadManyResult; releaseLock(): void; } @@ -2852,20 +1664,6 @@ interface ReadableWritablePair { } /** 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 backpressure and queuing. */ -interface WritableStream { - readonly locked: boolean; - abort(reason?: any): Promise; - close(): Promise; - getWriter(): WritableStreamDefaultWriter; -} - -declare var WritableStream: { - prototype: WritableStream; - new ( - underlyingSink?: UnderlyingSink, - strategy?: QueuingStrategy, - ): WritableStream; -}; /** 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 { @@ -2893,86 +1691,87 @@ declare var WritableStreamDefaultWriter: { new (stream: WritableStream): WritableStreamDefaultWriter; }; -interface ReadWriteStream extends ReadableStream, WritableStream {} +declare namespace Bun { + // interface ReadWriteStream extends ReadableStream, WritableStream {} -interface TransformerFlushCallback { - (controller: TransformStreamDefaultController): void | PromiseLike; + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + + interface TransformerTransformCallback { + ( + chunk: I, + controller: TransformStreamDefaultController, + ): 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 UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined | "default" | "bytes"; + write?: UnderlyingSinkWriteCallback; + } + + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + /** + * Mode "bytes" is not currently supported. + */ + type?: undefined; + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + interface DirectUnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull: ( + controller: ReadableStreamDirectController, + ) => void | PromiseLike; + type: "direct"; + } + + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + + interface GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } } - -interface TransformerStartCallback { - (controller: TransformStreamDefaultController): any; -} - -interface TransformerTransformCallback { - ( - chunk: I, - controller: TransformStreamDefaultController, - ): 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 UnderlyingSink { - abort?: UnderlyingSinkAbortCallback; - close?: UnderlyingSinkCloseCallback; - start?: UnderlyingSinkStartCallback; - type?: undefined | "default" | "bytes"; - write?: UnderlyingSinkWriteCallback; -} - -interface UnderlyingSource { - cancel?: UnderlyingSourceCancelCallback; - pull?: UnderlyingSourcePullCallback; - start?: UnderlyingSourceStartCallback; - /** - * Mode "bytes" is not currently supported. - */ - type?: undefined; -} - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -interface DirectUnderlyingSource { - cancel?: UnderlyingSourceCancelCallback; - pull: ( - controller: ReadableStreamDirectController, - ) => void | PromiseLike; - type: "direct"; -} - -interface UnderlyingSourcePullCallback { - (controller: ReadableStreamController): void | PromiseLike; -} - -interface UnderlyingSourceStartCallback { - (controller: ReadableStreamController): any; -} - -interface GenericTransformStream { - readonly readable: ReadableStream; - readonly writable: WritableStream; -} - interface TransformStream { readonly readable: ReadableStream; readonly writable: WritableStream; @@ -3039,10 +1838,10 @@ interface QueuingStrategySize { } interface Transformer { - flush?: TransformerFlushCallback; + flush?: Bun.TransformerFlushCallback; readableType?: undefined; - start?: TransformerStartCallback; - transform?: TransformerTransformCallback; + start?: Bun.TransformerStartCallback; + transform?: Bun.TransformerTransformCallback; writableType?: undefined; } @@ -3067,363 +1866,76 @@ interface DOMException extends Error { readonly code: number; readonly message: string; readonly name: string; - readonly ABORT_ERR: number; - readonly DATA_CLONE_ERR: number; - readonly DOMSTRING_SIZE_ERR: number; - readonly HIERARCHY_REQUEST_ERR: number; - readonly INDEX_SIZE_ERR: number; - readonly INUSE_ATTRIBUTE_ERR: number; - readonly INVALID_ACCESS_ERR: number; - readonly INVALID_CHARACTER_ERR: number; - readonly INVALID_MODIFICATION_ERR: number; - readonly INVALID_NODE_TYPE_ERR: number; - readonly INVALID_STATE_ERR: number; - readonly NAMESPACE_ERR: number; - readonly NETWORK_ERR: number; - readonly NOT_FOUND_ERR: number; - readonly NOT_SUPPORTED_ERR: number; - readonly NO_DATA_ALLOWED_ERR: number; - readonly NO_MODIFICATION_ALLOWED_ERR: number; - readonly QUOTA_EXCEEDED_ERR: number; - readonly SECURITY_ERR: number; - readonly SYNTAX_ERR: number; - readonly TIMEOUT_ERR: number; - readonly TYPE_MISMATCH_ERR: number; - readonly URL_MISMATCH_ERR: number; - readonly VALIDATION_ERR: number; - readonly WRONG_DOCUMENT_ERR: number; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; } -declare var DOMException: { - prototype: DOMException; - new (message?: string, name?: string): DOMException; -}; +declare var DOMException: typeof globalThis extends { + onerror: any; + DOMException: infer T; +} + ? T + : { + prototype: DOMException; + new (message?: string, name?: string): DOMException; + }; declare function alert(message?: string): void; declare function confirm(message?: string): boolean; declare function prompt(message?: string, _default?: string): string | null; -/* - - Web Crypto API - -*/ - -type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; -type KeyType = "private" | "public" | "secret"; -type KeyUsage = - | "decrypt" - | "deriveBits" - | "deriveKey" - | "encrypt" - | "sign" - | "unwrapKey" - | "verify" - | "wrapKey"; -type HashAlgorithmIdentifier = AlgorithmIdentifier; -type NamedCurve = string; - -type BigInteger = Uint8Array; - -interface KeyAlgorithm { - name: string; +declare namespace Bun { + type _SubtleCrypto = typeof globalThis extends { + onerror: any; + SubtleCrypto: infer T; + } + ? T + : import("crypto").webcrypto.SubtleCrypto; } - -interface Algorithm { - name: string; -} - -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 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 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 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 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 CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -type AlgorithmIdentifier = Algorithm | string; - -/** - * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). - */ -interface SubtleCrypto { - decrypt( - algorithm: - | AlgorithmIdentifier - | RsaOaepParams - | AesCtrParams - | AesCbcParams - | AesGcmParams, - key: CryptoKey, - data: BufferSource, - ): Promise; - deriveBits( - algorithm: - | AlgorithmIdentifier - | EcdhKeyDeriveParams - | HkdfParams - | Pbkdf2Params, - baseKey: CryptoKey, - length: number, - ): Promise; - deriveKey( - algorithm: - | AlgorithmIdentifier - | EcdhKeyDeriveParams - | HkdfParams - | Pbkdf2Params, - baseKey: CryptoKey, - derivedKeyType: - | AlgorithmIdentifier - | AesDerivedKeyParams - | HmacImportParams - | HkdfParams - | Pbkdf2Params, - extractable: boolean, - keyUsages: KeyUsage[], - ): Promise; - digest( - algorithm: AlgorithmIdentifier, - data: BufferSource, - ): Promise; - encrypt( - algorithm: - | AlgorithmIdentifier - | RsaOaepParams - | AesCtrParams - | AesCbcParams - | AesGcmParams, - key: CryptoKey, - data: BufferSource, - ): Promise; - exportKey(format: "jwk", key: CryptoKey): Promise; - exportKey( - format: Exclude, - key: CryptoKey, - ): Promise; - 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; - 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; - sign( - algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, - key: CryptoKey, - data: BufferSource, - ): Promise; - unwrapKey( - format: KeyFormat, - wrappedKey: BufferSource, - unwrappingKey: CryptoKey, - unwrapAlgorithm: - | AlgorithmIdentifier - | RsaOaepParams - | AesCtrParams - | AesCbcParams - | AesGcmParams, - unwrappedKeyAlgorithm: - | AlgorithmIdentifier - | RsaHashedImportParams - | EcKeyImportParams - | HmacImportParams - | AesKeyAlgorithm, - extractable: boolean, - keyUsages: KeyUsage[], - ): Promise; - verify( - algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, - key: CryptoKey, - signature: BufferSource, - data: BufferSource, - ): Promise; - wrapKey( - format: KeyFormat, - key: CryptoKey, - wrappingKey: CryptoKey, - wrapAlgorithm: - | AlgorithmIdentifier - | RsaOaepParams - | AesCtrParams - | AesCbcParams - | AesGcmParams, - ): Promise; -} - -declare var SubtleCrypto: { - prototype: SubtleCrypto; - new (): SubtleCrypto; -}; - -interface RsaPssParams extends Algorithm { - saltLength: number; +declare var SubtleCrypto: typeof globalThis extends { + onerror: any; + SubtleCrypto: infer T; } + ? T + : { + prototype: Bun._SubtleCrypto; + new (): Bun._SubtleCrypto; + }; /** * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. */ -interface CryptoKey { - readonly algorithm: KeyAlgorithm; - readonly extractable: boolean; - readonly type: KeyType; - readonly usages: KeyUsage[]; +declare namespace Bun { + type _CryptoKey = typeof globalThis extends { + onerror: any; + CryptoKey: infer T; + } + ? T + : import("crypto").webcrypto.CryptoKey; } +interface CryptoKey extends Bun._CryptoKey {} declare var CryptoKey: { prototype: CryptoKey; @@ -3483,6 +1995,7 @@ declare var ResolveError: typeof ResolveMessage; // Declare "static" methods in Error interface ErrorConstructor { /** Create .stack property on a target object */ + // eslint-disable-next-line @typescript-eslint/ban-types captureStackTrace(targetObject: object, constructorOpt?: Function): void; /** @@ -3491,86 +2004,12 @@ interface ErrorConstructor { * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces */ prepareStackTrace?: - | ((err: Error, stackTraces: CallSite[]) => any) + | ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; stackTraceLimit: number; } -interface CallSite { - /** - * Value of "this" - */ - getThis(): unknown; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; -} - interface ArrayBufferConstructor { new (byteLength: number, options: { maxByteLength?: number }): ArrayBuffer; } @@ -3599,145 +2038,279 @@ interface SharedArrayBuffer { grow(size: number): SharedArrayBuffer; } +declare namespace Bun { + namespace WebAssembly { + type ImportExportKind = "function" | "global" | "memory" | "table"; + type TableKind = "anyfunc" | "externref"; + // eslint-disable-next-line @typescript-eslint/ban-types + type ExportValue = + | Function + | Global + | WebAssembly.Memory + | WebAssembly.Table; + type Exports = Record; + type ImportValue = ExportValue | number; + type Imports = Record; + type ModuleImports = Record; + + interface ValueTypeMap { + // eslint-disable-next-line @typescript-eslint/ban-types + anyfunc: Function; + externref: any; + f32: number; + f64: number; + i32: number; + i64: bigint; + v128: never; + } + + type ValueType = keyof ValueTypeMap; + + interface GlobalDescriptor { + mutable?: boolean; + value: T; + } + + interface Global { + // { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/value) */ + value: ValueTypeMap[T]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/valueOf) */ + valueOf(): ValueTypeMap[T]; + } + type _Global = typeof globalThis extends { + onerror: any; + WebAssembly: { Global: infer T }; + } + ? T + : Global; + + interface CompileError extends Error {} + type _CompileError = typeof globalThis extends { + onerror: any; + WebAssembly: { CompileError: infer T }; + } + ? T + : CompileError; + + interface LinkError extends Error {} + type _LinkError = typeof globalThis extends { + onerror: any; + WebAssembly: { LinkError: infer T }; + } + ? T + : LinkError; + + interface RuntimeError extends Error {} + type _RuntimeError = typeof globalThis extends { + onerror: any; + WebAssembly: { RuntimeError: infer T }; + } + ? T + : RuntimeError; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance) */ + interface Instance { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports) */ + readonly exports: Exports; + } + type _Instance = typeof globalThis extends { + onerror: any; + WebAssembly: { Instance: infer T }; + } + ? T + : Instance; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) */ + interface Memory { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/buffer) */ + readonly buffer: ArrayBuffer; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/grow) */ + grow(delta: number): number; + } + type _Memory = typeof globalThis extends { + onerror: any; + WebAssembly: { Memory: infer T }; + } + ? T + : Memory; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) */ + interface Module {} + type _Module = typeof globalThis extends { + onerror: any; + WebAssembly: { Module: infer T }; + } + ? T + : Module; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table) */ + interface Table { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/length) */ + readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get) */ + get(index: number): any; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/grow) */ + grow(delta: number, value?: any): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/set) */ + set(index: number, value?: any): void; + } + type _Table = typeof globalThis extends { + onerror: any; + WebAssembly: { Table: infer T }; + } + ? T + : Table; + + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + + interface WebAssemblyInstantiatedSource { + instance: Instance; + module: Module; + } + } +} + declare namespace WebAssembly { - interface CompileError extends Error {} - - var CompileError: { - prototype: CompileError; - new (message?: string): CompileError; - (message?: string): CompileError; - }; - - interface Global { - value: any; - valueOf(): any; - } - - var Global: { - prototype: Global; - new (descriptor: GlobalDescriptor, v?: any): Global; - }; - - interface Instance { - readonly exports: Exports; - } - - var Instance: { - prototype: Instance; - new (module: Module, importObject?: Imports): Instance; - }; - - interface LinkError extends Error {} + interface ValueTypeMap extends Bun.WebAssembly.ValueTypeMap {} + interface GlobalDescriptor + extends Bun.WebAssembly.GlobalDescriptor {} + interface MemoryDescriptor extends Bun.WebAssembly.MemoryDescriptor {} + interface ModuleExportDescriptor + extends Bun.WebAssembly.ModuleExportDescriptor {} + interface ModuleImportDescriptor + extends Bun.WebAssembly.ModuleImportDescriptor {} + interface TableDescriptor extends Bun.WebAssembly.TableDescriptor {} + interface WebAssemblyInstantiatedSource + extends Bun.WebAssembly.WebAssemblyInstantiatedSource {} + interface LinkError extends Bun.WebAssembly._LinkError {} var LinkError: { prototype: LinkError; new (message?: string): LinkError; (message?: string): LinkError; }; - interface Memory { - readonly buffer: ArrayBuffer; - grow(delta: number): number; + interface CompileError extends Bun.WebAssembly._CompileError {} + var CompileError: typeof globalThis extends { + onerror: any; + WebAssembly: { CompileError: infer T }; } + ? T + : { + prototype: CompileError; + new (message?: string): CompileError; + (message?: string): CompileError; + }; - var Memory: { - prototype: Memory; - new (descriptor: MemoryDescriptor): Memory; - }; - - interface Module {} - - var Module: { - prototype: Module; - new (bytes: BufferSource): Module; - customSections(moduleObject: Module, sectionName: string): ArrayBuffer[]; - exports(moduleObject: Module): ModuleExportDescriptor[]; - imports(moduleObject: Module): ModuleImportDescriptor[]; - }; - - interface RuntimeError extends Error {} - + interface RuntimeError extends Bun.WebAssembly._RuntimeError {} var RuntimeError: { prototype: RuntimeError; new (message?: string): RuntimeError; (message?: string): RuntimeError; }; - interface Table { - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; + interface Global + extends Bun.WebAssembly._Global {} + var Global: typeof globalThis extends { + onerror: any; + WebAssembly: { Global: infer T }; } + ? T + : { + prototype: Global; + new ( + descriptor: GlobalDescriptor, + v?: ValueTypeMap[T], + ): Global; + }; + interface Instance extends Bun.WebAssembly._Instance {} + var Instance: typeof globalThis extends { + onerror: any; + WebAssembly: { Instance: infer T }; + } + ? T + : { + prototype: Instance; + new (module: Module, importObject?: Bun.WebAssembly.Imports): Instance; + }; + + interface Memory extends Bun.WebAssembly._Memory {} + var Memory: { + prototype: Memory; + new (descriptor: MemoryDescriptor): Memory; + }; + + interface Module extends Bun.WebAssembly._Module {} + var Module: typeof globalThis extends { + onerror: any; + WebAssembly: { Module: infer T }; + } + ? T + : { + prototype: Module; + new (bytes: Bun.BufferSource): Module; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/customSections) */ + customSections( + moduleObject: Module, + sectionName: string, + ): ArrayBuffer[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/exports) */ + exports(moduleObject: Module): ModuleExportDescriptor[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/imports) */ + imports(moduleObject: Module): ModuleImportDescriptor[]; + }; + + interface Table extends Bun.WebAssembly._Table {} var Table: { prototype: Table; new (descriptor: TableDescriptor, value?: any): Table; }; - interface GlobalDescriptor { - mutable?: boolean; - value: ValueType; - } - - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - - interface WebAssemblyInstantiatedSource { - instance: Instance; - module: Module; - } - - type ImportExportKind = "function" | "global" | "memory" | "table"; - type TableKind = "anyfunc" | "externref"; - type ValueType = - | "anyfunc" - | "externref" - | "f32" - | "f64" - | "i32" - | "i64" - | "v128"; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - type ImportValue = ExportValue | number; - type Imports = Record; - type ModuleImports = Record; - function compile(bytes: BufferSource): Promise; - // function compileStreaming(source: Response | PromiseLike): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile) */ + function compile(bytes: Bun.BufferSource): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming) */ + function compileStreaming( + source: Response | PromiseLike, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) */ function instantiate( - bytes: BufferSource, - importObject?: Imports, + bytes: Bun.BufferSource, + importObject?: Bun.WebAssembly.Imports, ): Promise; function instantiate( moduleObject: Module, - importObject?: Imports, + importObject?: Bun.WebAssembly.Imports, ): Promise; - // function instantiateStreaming( - // source: Response | PromiseLike, - // importObject?: Imports, - // ): Promise; - function validate(bytes: BufferSource): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming) */ + function instantiateStreaming( + source: Response | PromiseLike, + importObject?: Bun.WebAssembly.Imports, + ): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate) */ + function validate(bytes: Bun.BufferSource): boolean; } interface NodeModule { @@ -3760,91 +2333,112 @@ declare module "*.toml" { export = contents; } -interface EventSourceEventMap { - error: Event; - message: MessageEvent; - open: Event; -} - /** * Post a message to the parent thread. * * Only useful in a worker thread; calling this from the main thread does nothing. */ -declare function postMessage(message: any, transfer?: Transferable[]): void; +declare function postMessage(message: any, transfer?: Bun.Transferable[]): void; -interface EventSource extends EventTarget { - onerror: ((this: EventSource, ev: ErrorEvent) => any) | null; - onmessage: ((this: EventSource, ev: MessageEvent) => any) | null; - onopen: ((this: EventSource, ev: Event) => any) | null; - /** Returns the state of this EventSource object's connection. It can have the values described below. */ - readonly readyState: number; - /** Returns the URL providing the event stream. */ - readonly url: string; - /** Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. - * - * Not supported in Bun - * - */ - readonly withCredentials: boolean; - /** Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. */ - close(): void; - readonly CLOSED: number; - readonly CONNECTING: number; - readonly OPEN: number; - addEventListener( - type: K, - listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, - options?: boolean | AddEventListenerOptions, - ): void; - addEventListener( - type: string, - listener: (this: EventSource, event: MessageEvent) => any, - options?: boolean | AddEventListenerOptions, - ): void; - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions, - ): void; - removeEventListener( - type: K, - listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, - options?: boolean | EventListenerOptions, - ): void; - removeEventListener( - type: string, - listener: (this: EventSource, event: MessageEvent) => any, - options?: boolean | EventListenerOptions, - ): void; - removeEventListener( - type: string, - listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions, - ): void; +declare namespace Bun { + interface EventSourceEventMap { + error: Event; + message: MessageEvent; + open: Event; + } - /** - * Keep the event loop alive while connection is open or reconnecting - * - * Not available in browsers - */ - ref(): void; + interface EventSource extends EventTarget { + onerror: ((this: EventSource, ev: Event) => any) | null; + onmessage: ((this: EventSource, ev: MessageEvent) => any) | null; + onopen: ((this: EventSource, ev: Event) => any) | null; + /** Returns the state of this EventSource object's connection. It can have the values described below. */ + readonly readyState: number; + /** Returns the URL providing the event stream. */ + readonly url: string; + /** Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * Not supported in Bun + */ + readonly withCredentials: boolean; + /** Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. */ + close(): void; + readonly CLOSED: 2; + readonly CONNECTING: 0; + readonly OPEN: 1; + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: (this: EventSource, event: MessageEvent) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: (this: EventSource, event: MessageEvent) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; - /** - * Do not keep the event loop alive while connection is open or reconnecting - * - * Not available in browsers - */ - unref(): void; + /** + * Keep the event loop alive while connection is open or reconnecting + * + * Not available in browsers + */ + ref(): void; + + /** + * Do not keep the event loop alive while connection is open or reconnecting + * + * Not available in browsers + */ + unref(): void; + } + + type _EventSource = typeof globalThis extends { + onerror: any; + EventSource: infer T; + } + ? T + : EventSource; } -declare var EventSource: { - prototype: EventSource; - new (url: string | URL, eventSourceInitDict?: EventSourceInit): EventSource; - readonly CLOSED: number; - readonly CONNECTING: number; - readonly OPEN: number; -}; +interface EventSourceInit { + withCredentials?: boolean; +} + +interface EventSource extends Bun._EventSource {} +declare var EventSource: typeof globalThis extends { + onerror: any; + EventSource: infer T; +} + ? T + : { + prototype: EventSource; + new ( + url: string | URL, + eventSourceInitDict?: EventSourceInit, + ): EventSource; + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + }; interface PromiseConstructor { /** @@ -3881,3 +2475,288 @@ interface Navigator { } declare var navigator: Navigator; + +interface BlobPropertyBag { + /** Set a default "type". Not yet implemented. */ + type?: string; + /** Not implemented in Bun yet. */ + // endings?: "transparent" | "native"; +} + +declare namespace Bun { + type NodeBlob = import("buffer").Blob; + interface Blob extends NodeBlob { + /** + * Read the data from the blob as a JSON object. + * + * This first decodes the data from UTF-8, then parses it as JSON. + */ + // eslint-disable-next-line @definitelytyped/no-unnecessary-generics + json(): Promise; + + /** + * Read the data from the blob as a {@link FormData} object. + * + * This first decodes the data from UTF-8, then parses it as a + * `multipart/form-data` body or a `application/x-www-form-urlencoded` body. + * + * The `type` property of the blob is used to determine the format of the + * body. + * + * This is a non-standard addition to the `Blob` API, to make it conform more + * closely to the `BodyMixin` API. + */ + formData(): Promise; + } + type _Blob = typeof globalThis extends { onerror: any; Blob: infer T } + ? T + : Blob; +} + +interface Blob extends Bun._Blob {} +declare var Blob: typeof globalThis extends { + onerror: any; + Blob: infer T; +} + ? T + : { + prototype: Blob; + /** + * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + * + * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects + * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + */ + new (parts?: Bun.BlobPart[], options?: BlobPropertyBag): Blob; + }; + +declare namespace Bun { + type _RequestInit = typeof globalThis extends { onerror: any } + ? {} + : import("undici-types").RequestInit; + type _ResponseInit = typeof globalThis extends { onerror: any } + ? {} + : import("undici-types").ResponseInit; + type _Request = typeof globalThis extends { onerror: any } + ? {} + : import("undici-types").Request; + type _Response = typeof globalThis extends { onerror: any } + ? {} + : import("undici-types").Response; +} +interface ResponseInit extends Bun._ResponseInit {} +interface RequestInit extends Bun._RequestInit {} +interface Request extends Bun._Request {} +declare var Request: typeof globalThis extends { + onerror: any; + Request: infer T; +} + ? T + : { + new (requestInfo: string, requestInit?: RequestInit): Request; + new (requestInfo: RequestInit & { url: string }): Request; + new (requestInfo: Request, requestInit?: RequestInit): Request; + prototype: Request; + }; + +declare namespace Bun { + type _File = typeof globalThis extends { onerror: any } + ? {} + : import("node:buffer").File; +} + +declare namespace Bun { + type _Body = typeof globalThis extends { onerror: any } + ? {} + : { + readonly body: ReadableStream | null; + readonly bodyUsed: boolean; + readonly arrayBuffer: () => Promise; + readonly blob: () => Promise; + readonly formData: () => Promise; + readonly json: () => Promise; + readonly text: () => Promise; + }; +} +interface Body extends Bun._Body {} +interface Response extends Bun._Response {} +declare var Response: typeof globalThis extends { + onerror: any; + Response: infer T; +} + ? T + : { + prototype: Response; + new ( + body?: Bun.BodyInit | null | undefined, + init?: Bun.ResponseInit | undefined, + ): Response; + + /** + * Create a new {@link Response} with a JSON body + * + * @param body - The body of the response + * @param options - options to pass to the response + * + * @example + * + * ```ts + * const response = Response.json({hi: "there"}); + * console.assert( + * await response.text(), + * `{"hi":"there"}` + * ); + * ``` + * ------- + * + * This is syntactic sugar for: + * ```js + * new Response(JSON.stringify(body), {headers: { "Content-Type": "application/json" }}) + * ``` + * @link https://github.com/whatwg/fetch/issues/1389 + */ + json(body?: any, options?: Bun.ResponseInit | number): Response; + /** + * Create a new {@link Response} that redirects to url + * + * @param url - the URL to redirect to + * @param status - the HTTP status code to use for the redirect + */ + // tslint:disable-next-line:unified-signatures + redirect(url: string, status?: number): Response; + + /** + * Create a new {@link Response} that redirects to url + * + * @param url - the URL to redirect to + * @param options - options to pass to the response + */ + // tslint:disable-next-line:unified-signatures + redirect(url: string, options?: Bun.ResponseInit): Response; + + /** + * Create a new {@link Response} that has a network error + */ + error(): Response; + }; + +declare namespace Bun { + type _FormData = typeof globalThis extends { onerror: any; FormData: infer T } + ? T + : import("undici-types").FormData; +} +interface FormData extends Bun._FormData {} +declare var FormData: typeof globalThis extends { + onerror: any; + FormData: infer T; +} + ? T + : typeof import("undici-types").FormData; + +declare namespace Bun { + type _Headers = typeof globalThis extends { onerror: any; Headers: infer T } + ? T + : import("undici-types").Headers; +} +interface Headers extends Bun._Headers {} +declare var Headers: typeof globalThis extends { + onerror: any; + Headers: infer T; +} + ? T + : typeof import("undici-types").Headers; + +declare namespace Bun { + type _MessagePort = typeof globalThis extends { + onerror: any; + MessagePort: infer T; + } + ? T + : import("worker_threads").MessagePort; + type _MessageChannel = typeof globalThis extends { + onerror: any; + MessageChannel: infer T; + } + ? T + : import("worker_threads").MessageChannel; + type _BroadcastChannel = typeof globalThis extends { + onerror: any; + BroadcastChannel: infer T; + } + ? T + : import("worker_threads").BroadcastChannel; +} +interface MessagePort extends Bun._MessagePort {} +declare var MessagePort: typeof globalThis extends { + onerror: any; + MessagePort: infer T; +} + ? T + : { + prototype: MessagePort; + new (): MessagePort; + }; +interface MessageChannel extends Bun._MessageChannel {} +declare var MessageChannel: typeof globalThis extends { + onerror: any; + MessageChannel: infer T; +} + ? T + : { + prototype: MessageChannel; + new (): MessageChannel; + }; + +interface BroadcastChannel extends Bun._BroadcastChannel {} +declare var BroadcastChannel: typeof globalThis extends { + onerror: any; + BroadcastChannel: infer T; +} + ? T + : { + prototype: BroadcastChannel; + new (name: string): BroadcastChannel; + }; + +// declare namespace Bun { +// type _AbortSignal = typeof globalThis extends { +// onerror: any; +// AbortSignal: infer T; +// } +// ? T +// : import("") +// } +/** + * No `namespace Bun` shenanigans is necessary here because AbortController and AbortSignal interfaces are + * globals in ` + */ + +declare var AbortController: typeof globalThis extends { + onerror: any; + AbortController: infer T; +} + ? T + : { + prototype: AbortController; + new (): AbortController; + }; + +declare var AbortSignal: typeof globalThis extends { + onerror: any; + AbortSignal: infer T; +} + ? T + : { + prototype: AbortSignal; + new (): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + +declare namespace Bun { + type ArrayBufferView = TypedArray | DataView; + type StringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLike; + type PathLike = string | NodeJS.TypedArray | ArrayBufferLike | URL; +} + +declare var Bun: typeof import("bun"); diff --git a/packages/bun-types/header.txt b/packages/bun-types/header.txt index 0488d730ae..4190d60722 100644 --- a/packages/bun-types/header.txt +++ b/packages/bun-types/header.txt @@ -2,7 +2,9 @@ // Project: https://github.com/oven-sh/bun // Definitions by: Jarred Sumner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /// +/// +/// // This file is bundled so that your TypeScript editor integration loads it faster. diff --git a/packages/bun-types/http.d.ts b/packages/bun-types/http.d.ts deleted file mode 100644 index 118cf7ac1a..0000000000 --- a/packages/bun-types/http.d.ts +++ /dev/null @@ -1,1823 +0,0 @@ -/** - * 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': 'example.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', 'example.com', - * 'accepT', '*' ] - * ``` - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/http.js) - */ -declare module "http" { - import * as stream from "node:stream"; - - import { Socket, TcpSocketConnectOpts, Server as NetServer } from "node:net"; - - // incoming headers will never contain number - interface IncomingHttpHeaders extends Dict { - accept?: string | undefined; - "accept-language"?: string | undefined; - "accept-patch"?: string | undefined; - "accept-ranges"?: string | undefined; - "access-control-allow-credentials"?: string | undefined; - "access-control-allow-headers"?: string | undefined; - "access-control-allow-methods"?: string | undefined; - "access-control-allow-origin"?: string | undefined; - "access-control-expose-headers"?: string | undefined; - "access-control-max-age"?: string | undefined; - "access-control-request-headers"?: string | undefined; - "access-control-request-method"?: string | undefined; - age?: string | undefined; - allow?: string | undefined; - "alt-svc"?: string | undefined; - authorization?: string | undefined; - "cache-control"?: string | undefined; - connection?: string | undefined; - "content-disposition"?: string | undefined; - "content-encoding"?: string | undefined; - "content-language"?: string | undefined; - "content-length"?: string | undefined; - "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; - "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; - "proxy-authenticate"?: string | undefined; - "proxy-authorization"?: string | undefined; - "public-key-pins"?: string | undefined; - range?: string | undefined; - referer?: string | undefined; - "retry-after"?: string | undefined; - "sec-websocket-accept"?: string | undefined; - "sec-websocket-extensions"?: string | undefined; - "sec-websocket-key"?: string | undefined; - "sec-websocket-protocol"?: string | undefined; - "sec-websocket-version"?: string | undefined; - "set-cookie"?: string[] | undefined; - "strict-transport-security"?: string | undefined; - tk?: string | undefined; - trailer?: string | undefined; - "transfer-encoding"?: string | undefined; - upgrade?: string | undefined; - "user-agent"?: 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 Dict {} - interface ClientRequestArgs { - agent?: Agent | boolean | undefined; - auth?: string | null | undefined; - // createConnection?: - // | (( - // options: ClientRequestArgs, - // oncreate: (err: Error, socket: Socket) => void, - // ) => Socket) - // | undefined; - defaultPort?: number | string | undefined; - family?: number | undefined; - headers?: OutgoingHttpHeaders | undefined; - // hints?: LookupOptions["hints"]; - host?: string | null | undefined; - hostname?: string | null | undefined; - // insecureHTTPParser?: boolean | undefined; - localAddress?: string | undefined; - // localPort?: number | undefined; - // lookup?: LookupFunction | undefined; - /** - * @default 8192 - */ - maxHeaderSize?: number | undefined; - method?: string | undefined; - path?: string | null | undefined; - port?: number | string | null | undefined; - protocol?: string | null | undefined; - setHost?: boolean | undefined; - signal?: AbortSignal | undefined; - socketPath?: string | undefined; - timeout?: number | undefined; - // uniqueHeaders?: Array | undefined; - } - - interface ServerOptions< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - > { - /** - * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. - */ - IncomingMessage?: Request | undefined; - /** - * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. - */ - ServerResponse?: Response | undefined; - /** - * Sets the timeout value in milliseconds for receiving the entire request from the client. - * @see Server.requestTimeout for more information. - * @default 300000 - * @since v18.0.0 - */ - requestTimeout?: number | undefined; - /** - * The number of milliseconds of inactivity a server needs to wait for additional incoming data, - * after it has finished writing the last response, before a socket will be destroyed. - * @see Server.keepAliveTimeout for more information. - * @default 5000 - * @since v18.0.0 - */ - keepAliveTimeout?: number | undefined; - /** - * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. - * @default 30000 - */ - connectionsCheckingInterval?: number | undefined; - /** - * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. - * Using the insecure parser should be avoided. - * See --insecure-http-parser for more information. - * @default false - */ - insecureHTTPParser?: boolean | undefined; - /** - * Optionally overrides the value of - * `--max-http-header-size` for requests received by this server, i.e. - * the maximum length of request headers in bytes. - * @default 16384 - * @since v13.3.0 - */ - maxHeaderSize?: number | undefined; - /** - * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. - * @default true - * @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; - /** - * A list of response headers that should be sent only once. - * If the header's value is an array, the items will be joined using `; `. - */ - uniqueHeaders?: Array | undefined; - } - 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 - */ - var Server: Server; - interface Server< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - > extends NetServer { - prototype: Server; - - new ( - requestListener?: RequestListener, - ): Server; - new ( - options: ServerOptions, - requestListener?: RequestListener, - ): Server; - /** - * 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. - * @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. - * - * 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 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. - * - * 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; - /** - * Closes all connections connected to this server. - * @since v18.2.0 - */ - // closeAllConnections(): void; - /** - * Closes all connections connected to this server which are not sending a request or waiting for a response. - * @since v18.2.0 - */ - // closeIdleConnections(): void; - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "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: "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: 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: 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: 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: "clientError", - listener: (err: Error, socket: stream.Duplex) => 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: "clientError", - listener: (err: Error, socket: stream.Duplex) => 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: "clientError", - // listener: (err: Error, socket: stream.Duplex) => 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: "clientError", - // listener: (err: Error, socket: stream.Duplex) => 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; - } - /** - * 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< - Request extends IncomingMessage = IncomingMessage, - > extends stream.Writable { - readonly req: Request; - chunkedEncoding: boolean; - shouldKeepAlive: boolean; - useChunkedEncodingByDefault: boolean; - sendDate: boolean; - /** - * @deprecated Use `writableEnded` instead. - */ - finished: boolean; - /** - * Read-only. `true` if the headers were sent, otherwise `false`. - * @since v0.9.3 - */ - readonly headersSent: boolean; - /** - * Aliases of `outgoingMessage.socket` - * @since v0.3.0 - * @deprecated Since v15.12.0,v14.17.1 - 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 v7.7.0 - */ - getHeaders(): OutgoingHttpHeaders; - /** - * Returns an array of names of headers of the outgoing outgoingMessage. All - * names are lowercase. - * @since v7.7.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 v7.7.0 - */ - hasHeader(name: string): boolean; - /** - * Removes a header that is queued for implicit sending. - * - * ```js - * outgoingMessage.removeHeader('Content-Encoding'); - * ``` - * @since v0.4.0 - * @param name Header name - */ - 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; - } - /** - * 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< - Request extends IncomingMessage = IncomingMessage, - > 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: Request); - assignSocket(socket: Socket): void; - detachSocket(socket: Socket): void; - /** - * Sends an 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; - /** - * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, - * indicating that the user agent can preload/preconnect the linked resources. - * The `hints` is an object containing the values of headers to be sent with - * early hints message. The optional `callback` argument will be called when - * the response message has been written. - * - * Example: - * - * ```js - * const earlyHintsLink = '; rel=preload; as=style'; - * response.writeEarlyHints({ - * 'link': earlyHintsLink, - * }); - * - * const earlyHintsLinks = [ - * '; rel=preload; as=style', - * '; rel=preload; as=script', - * ]; - * response.writeEarlyHints({ - * 'link': earlyHintsLinks, - * 'x-trace-id': 'id for diagnostics' - * }); - * - * const earlyHintsCallback = () => console.log('early hints message sent'); - * response.writeEarlyHints({ - * 'link': earlyHintsLinks - * }, earlyHintsCallback); - * ``` - * - * @since v18.11.0 - * @param hints An object containing the values of headers - * @param callback Will be called when the response message has been written - */ - writeEarlyHints( - hints: Record, - callback?: () => void, - ): 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. - * 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 an 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; - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - headers: IncomingHttpHeaders; - rawHeaders: string[]; - } - /** - * 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. - */ - class ClientRequest extends OutgoingMessage { - /** - * The `request.aborted` property will be `true` if the request has - * been aborted. - * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. - */ - aborted: boolean; - /** - * The request host. - */ - host: string; - /** - * The request protocol. - */ - protocol: string; - /** - * When sending request through a keep-alive enabled agent, the underlying socket - * might be reused. But if server closes connection at unfortunate time, client - * may run into a 'ECONNRESET' error. - * - * ```js - * const http = require('http'); - * - * // Server has a 5 seconds keep-alive timeout by default - * http - * .createServer((req, res) => { - * res.write('hello\n'); - * res.end(); - * }) - * .listen(3000); - * - * setInterval(() => { - * // Adapting a keep-alive agent - * http.get('http://localhost:3000', { agent }, (res) => { - * res.on('data', (data) => { - * // Do nothing - * }); - * }); - * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout - * ``` - * - * By marking a request whether it reused socket or not, we can do - * automatic error retry base on it. - * - * ```js - * const http = require('http'); - * const agent = new http.Agent({ keepAlive: true }); - * - * function retriableRequest() { - * const req = http - * .get('http://localhost:3000', { agent }, (res) => { - * // ... - * }) - * .on('error', (err) => { - * // Check if retry is needed - * if (req.reusedSocket && err.code === 'ECONNRESET') { - * retriableRequest(); - * } - * }); - * } - * - * retriableRequest(); - * ``` - */ - // reusedSocket: boolean; - /** - * Limits maximum response headers count. If set to 0, no limit will be applied. - */ - // maxHeadersCount: number; - constructor( - url: string | URL | ClientRequestArgs, - cb?: (res: IncomingMessage) => void, - ); - /** - * The request method. - */ - method: string; - /** - * The request path. - */ - path: string; - /** - * Marks the request as aborting. Calling this will cause remaining data - * in the response to be dropped and the socket to be destroyed. - * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. - */ - abort(): void; - /** - * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. - * @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; - /** - * Sets a single header value for the header object. - * @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`. - * @param name Name of header - */ - getHeader(name: string): number | string | string[] | undefined; - /** - * Removes a header that is queued for implicit sending. - * - * ```js - * outgoingMessage.removeHeader('Content-Encoding'); - * ``` - * @param name Header name - */ - removeHeader(name: 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. - */ - flushHeaders(): void; - /** - * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. - */ - // setNoDelay(noDelay?: boolean): void; - /** - * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. - */ - 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'] - * ``` - */ - // getRawHeaderNames(): string[]; - /** - * @deprecated - */ - addListener(event: "abort", listener: () => 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: "timeout", listener: () => 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: stream.Readable) => void): this; - addListener( - event: "unpipe", - listener: (src: stream.Readable) => void, - ): this; - addListener( - event: string | symbol, - listener: (...args: any[]) => void, - ): this; - /** - * @deprecated - */ - on(event: "abort", listener: () => void): this; - on(event: "continue", listener: () => void): this; - on(event: "information", listener: (info: InformationEvent) => void): this; - on(event: "response", listener: (response: IncomingMessage) => void): this; - on(event: "timeout", listener: () => 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: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - /** - * @deprecated - */ - once(event: "abort", listener: () => void): this; - once(event: "continue", listener: () => void): this; - once( - event: "information", - listener: (info: InformationEvent) => void, - ): this; - once( - event: "response", - listener: (response: IncomingMessage) => void, - ): this; - once(event: "timeout", listener: () => 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: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - /** - * @deprecated - */ - prependListener(event: "abort", listener: () => 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: "timeout", listener: () => 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: stream.Readable) => void, - ): this; - prependListener( - event: "unpipe", - listener: (src: stream.Readable) => void, - ): this; - prependListener( - event: string | symbol, - listener: (...args: any[]) => void, - ): this; - /** - * @deprecated - */ - prependOnceListener(event: "abort", listener: () => 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: "timeout", listener: () => 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: stream.Readable) => void, - ): this; - 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. - */ - class IncomingMessage extends stream.Readable { - /** - * The `message.aborted` property will be `true` if the request has - * been aborted. - * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. - */ - 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. - */ - 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'); - * }); - * }); - * ``` - */ - 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.getHeaders()); - * ``` - * - * 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 ', '. - */ - 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); - * ``` - */ - rawHeaders: string[]; - /** - * The request/response trailers object. Only populated at the `'end'` event. - */ - trailers: Dict; - /** - * The raw request/response trailer keys and values exactly as they were - * received. Only populated at the `'end'` event. - */ - rawTrailers: string[]; - /** - * Calls `message.socket.setTimeout(msecs, callback)`. - */ - setTimeout(msecs: number, callback?: () => void): this; - /** - * **Only valid for request obtained from {@link Server}.** - * - * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. - */ - method?: string | undefined; - /** - * **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.getHeaders().host}`); - * ``` - * - * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: - * - * ```console - * $ node - * > new URL(request.url, `http://${request.getHeaders().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: '' - * } - * ``` - */ - url: string | undefined; - /** - * **Only valid for response obtained from {@link ClientRequest}.** - * - * The 3-digit HTTP response status code. E.G. `404`. - */ - statusCode?: number | undefined; - /** - * **Only valid for response obtained from {@link ClientRequest}.** - * - * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. - */ - 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. - */ - destroy(error?: Error): this; - } - - interface AgentOptions extends Partial { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean | undefined; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number | undefined; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number | undefined; - /** - * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. - */ - maxTotalSockets?: number | undefined; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number | undefined; - /** - * Socket timeout in milliseconds. This will set the timeout after the socket is connected. - */ - // timeout?: number | undefined; - /** - * 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: ReadOnlyDict; - /** - * An object which contains arrays of sockets currently in use by the - * agent. Do not modify. - * @since v0.3.6 - */ - readonly sockets: 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: 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 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; - keepSocketAlive(socket: Socket): boolean; - } - - const METHODS: string[]; - const STATUS_CODES: { - [errorCode: number]: string | undefined; - [errorCode: string]: string | undefined; - }; - - /** - * 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 {} - /** - * `options` in `socket.connect()` are also supported. - * - * 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. - */ - function request( - options: RequestOptions | string | URL, - 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); - * ``` - * @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; - - /** - * 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; - - 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. - */ - const maxHeaderSize: number; -} -declare module "node:http" { - export * from "http"; -} -// XXX: temporary types till theres a proper http(s) module -declare module "https" { - export * from "http"; -} -declare module "node:https" { - export * from "http"; -} diff --git a/packages/bun-types/index.d.ts b/packages/bun-types/index.d.ts index e5f866c210..9880e10845 100644 --- a/packages/bun-types/index.d.ts +++ b/packages/bun-types/index.d.ts @@ -1,50 +1,18 @@ -/* eslint-disable */ -// Type definitions for bun 0.0 // Project: https://github.com/oven-sh/bun // Definitions by: Jarred Sumner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// + +// contributors: uncomment this to detect conflicts with lib.dom.d.ts +//// + /// +/// +/// +/// /// -/// /// -/// -/// -/// -/// -/// -/// -/// -/// -/// /// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/packages/bun-types/index.js b/packages/bun-types/index.js deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/bun-types/jsc.d.ts b/packages/bun-types/jsc.d.ts index 00a776cdd0..2a5f85eab2 100644 --- a/packages/bun-types/jsc.d.ts +++ b/packages/bun-types/jsc.d.ts @@ -1,14 +1,15 @@ declare module "bun:jsc" { + type AnyFunction = (..._: any[]) => any; + /** * This used to be called "describe" but it could be confused with the test runner. - */ - export function jscDescribe(value: any): string; - export function jscDescribeArray(args: any[]): string; - export function gcAndSweep(): number; - export function fullGC(): number; - export function edenGC(): number; - export function heapSize(): number; - export function heapStats(): { + */ function jscDescribe(value: any): string; + function jscDescribeArray(args: any[]): string; + function gcAndSweep(): number; + function fullGC(): number; + function edenGC(): number; + function heapSize(): number; + function heapStats(): { heapSize: number; heapCapacity: number; extraMemorySize: number; @@ -19,25 +20,25 @@ declare module "bun:jsc" { objectTypeCounts: Record; protectedObjectTypeCounts: Record; }; - export function memoryUsage(): { + function memoryUsage(): { current: number; peak: number; currentCommit: number; peakCommit: number; pageFaults: number; }; - export function getRandomSeed(): number; - export function setRandomSeed(value: number): void; - export function isRope(input: string): boolean; - export function callerSourceOrigin(): string; - export function noFTL(func: Function): Function; - export function noOSRExitFuzzing(func: Function): Function; - export function optimizeNextInvocation(func: Function): void; - export function numberOfDFGCompiles(func: Function): number; - export function releaseWeakRefs(): void; - export function totalCompileTime(func: Function): number; - export function reoptimizationRetryCount(func: Function): number; - export function drainMicrotasks(): void; + function getRandomSeed(): number; + function setRandomSeed(value: number): void; + function isRope(input: string): boolean; + function callerSourceOrigin(): string; + function noFTL(func: AnyFunction): AnyFunction; + function noOSRExitFuzzing(func: AnyFunction): AnyFunction; + function optimizeNextInvocation(func: AnyFunction): void; + function numberOfDFGCompiles(func: AnyFunction): number; + function releaseWeakRefs(): void; + function totalCompileTime(func: AnyFunction): number; + function reoptimizationRetryCount(func: AnyFunction): number; + function drainMicrotasks(): void; /** * Convert a JavaScript value to a binary representation that can be sent to another Bun instance. @@ -46,9 +47,7 @@ declare module "bun:jsc" { * * @param value A JavaScript value, usually an object or array, to be converted. * @returns A SharedArrayBuffer that can be sent to another Bun instance. - * - */ - export function serialize( + */ function serialize( value: any, options?: { binaryType?: "arraybuffer" }, ): SharedArrayBuffer; @@ -60,8 +59,7 @@ declare module "bun:jsc" { * * @param value A JavaScript value, usually an object or array, to be converted. * @returns A Buffer that can be sent to another Bun instance. - */ - export function serialize( + */ function serialize( value: any, options?: { binaryType: "nodebuffer" }, ): Buffer; @@ -70,10 +68,7 @@ declare module "bun:jsc" { * Convert an ArrayBuffer or Buffer to a JavaScript value compatible with the HTML Structured Clone Algorithm. * * @param value A serialized value, usually an ArrayBuffer or Buffer, to be converted. - */ - export function deserialize( - value: ArrayBufferLike | TypedArray | Buffer, - ): any; + */ function deserialize(value: ArrayBufferLike | TypedArray | Buffer): any; /** * Set the timezone used by Intl, Date, etc. @@ -84,8 +79,7 @@ declare module "bun:jsc" { * * You can also set process.env.TZ to the time zone you want to use. * You can also view the current timezone with `Intl.DateTimeFormat().resolvedOptions().timeZone` - */ - export function setTimeZone(timeZone: string): string; + */ function setTimeZone(timeZone: string): string; /** * Run JavaScriptCore's sampling profiler for a particular function @@ -97,8 +91,7 @@ declare module "bun:jsc" { * - Baseline is the first JIT compilation tier. It's the least optimized, but the fastest to compile * - DFG means "Data Flow Graph", which is the second JIT compilation tier. It has some optimizations, but is slower to compile * - FTL means "Faster Than Light", which is the third JIT compilation tier. It has the most optimizations, but is the slowest to compile - */ - export function profile( + */ function profile( callback: CallableFunction, sampleInterval?: number, ): { @@ -143,7 +136,6 @@ declare module "bun:jsc" { * C/C++: 0 (0.000000%) * Unknown Executable: 148 (2.158064%) * - * * Hottest bytecodes as * 273 'visit#:DFG:bc#63' * 121 'walk#:DFG:bc#7' @@ -205,8 +197,7 @@ declare module "bun:jsc" { * This function is mostly a debugging tool for bun itself. * * Warning: not all objects returned are supposed to be observable from JavaScript - */ - export function getProtectedObjects(): any[]; + */ function getProtectedObjects(): any[]; /** * Start a remote debugging socket server on the given port. @@ -214,11 +205,9 @@ declare module "bun:jsc" { * This exposes JavaScriptCore's built-in debugging server. * * This is untested. May not be supported yet on macOS - */ - export function startRemoteDebugger(host?: string, port?: number): void; + */ function startRemoteDebugger(host?: string, port?: number): void; /** * Run JavaScriptCore's sampling profiler - */ - export function startSamplingProfiler(optionalDirectory?: string): void; + */ function startSamplingProfiler(optionalDirectory?: string): void; } diff --git a/packages/bun-types/module.d.ts b/packages/bun-types/module.d.ts deleted file mode 100644 index 9795bd76cf..0000000000 --- a/packages/bun-types/module.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -declare module "node:module" { - export * from "module"; -} - -declare module "module" { - export function createRequire(filename: string): NodeJS.Require; - export function _resolveFilename( - path: string, - parent: string, - isMain: boolean, - ): string; - /** - * Bun's module cache is not exposed but this property exists for compatibility. - */ - export var _cache: {}; - - export var builtinModules: string[]; -} diff --git a/packages/bun-types/net.d.ts b/packages/bun-types/net.d.ts deleted file mode 100644 index 42d6df5d24..0000000000 --- a/packages/bun-types/net.d.ts +++ /dev/null @@ -1,1004 +0,0 @@ -/** - * > 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/v18.0.0/lib/net.js) - */ -declare module "net" { - 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: 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); - /** - * This function is called for every chunk of incoming data. - * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. - * Return false from this function to implicitly pause() the socket. - */ - 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. - * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will - * still be emitted as normal and methods like pause() and resume() will also behave as expected. - */ - onread?: OnReadOpts | undefined; - } - interface TcpSocketConnectOpts extends ConnectOpts { - port: number; - host?: string | undefined; - // localAddress?: string | undefined; - // localPort?: number | undefined; - // hints?: number | undefined; - // family?: number | undefined; - // lookup?: LookupFunction | undefined; - // noDelay?: boolean | undefined; - // keepAlive?: boolean | undefined; - // keepAliveInitialDelay?: number | undefined; - } - // 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); - /** - * 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; - /** - * Close the TCP connection by sending an RST packet and destroy the stream. - * If this TCP socket is in connecting status, it will send an RST packet - * and destroy this TCP socket once it is connected. Otherwise, it will call - * `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket - * (for example, a pipe), calling this method will immediately throw - * an `ERR_INVALID_HANDLE_TYPE` Error. - * @since v18.3.0 - * @return The socket itself. - */ - resetAndDestroy(): this; - /** - * Resumes reading after a call to `socket.pause()`. - * @return The socket itself. - */ - resume(): this; - /** - * Sets the socket to timeout after `timeout` milliseconds of inactivity on - * the socket. By default `net.Socket` do not have a timeout. - * - * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to - * end the connection. - * - * ```js - * socket.setTimeout(3000); - * socket.on('timeout', () => { - * console.log('socket timeout'); - * socket.end(); - * }); - * ``` - * - * If `timeout` is 0, then the existing idle timeout is disabled. - * - * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. - * @since v0.1.90 - * @return The socket itself. - */ - setTimeout(timeout: number, callback?: () => void): this; - /** - * Enable/disable the use of Nagle's algorithm. - * - * When a TCP connection is created, it will have Nagle's algorithm enabled. - * - * Nagle's algorithm delays data before it is sent via the network. It attempts - * to optimize throughput at the expense of latency. - * - * Passing `true` for `noDelay` or not passing an argument will disable Nagle's - * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's - * algorithm. - * @since v0.1.90 - * @param [noDelay=true] - * @return The socket itself. - */ - setNoDelay(noDelay?: boolean): this; - /** - * Enable/disable keep-alive functionality, and optionally set the initial - * delay before the first keepalive probe is sent on an idle socket. - * - * Set `initialDelay` (in milliseconds) to set the delay between the last - * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default - * (or previous) setting. - * - * Enabling the keep-alive functionality will set the following socket options: - * - * * `SO_KEEPALIVE=1` - * * `TCP_KEEPIDLE=initialDelay` - * * `TCP_KEEPCNT=10` - * * `TCP_KEEPINTVL=1` - * @since v0.1.92 - * @param [enable=false] - * @param [initialDelay=0] - * @return The socket itself. - */ - setKeepAlive(enable?: boolean, initialDelay?: number): this; - /** - * Returns the bound `address`, the address `family` name and `port` of the - * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` - * @since v0.1.90 - */ - address(): AddressInfo | {}; - /** - * Calling `unref()` on a socket will allow the program to exit if this is the only - * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. - * @since v0.9.1 - * @return The socket itself. - */ - unref(): this; - /** - * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). - * If the socket is `ref`ed calling `ref` again will have no effect. - * @since v0.9.1 - * @return The socket itself. - */ - ref(): this; - /** - * 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; - /** - * 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 - */ - readonly localFamily?: string; - /** - * 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; - /** - * 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 - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. ready - * 9. timeout - */ - addListener(event: string, listener: (...args: any[]) => 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", 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: (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: (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: (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: (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 extends Abortable { - port?: number | undefined; - host?: string | undefined; - backlog?: number | undefined; - path?: string | undefined; - exclusive?: boolean | undefined; - readableAll?: boolean | undefined; - writableAll?: boolean | undefined; - /** - * @default false - */ - ipv6Only?: boolean | 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; - } - interface DropArgument { - localAddress?: string; - localPort?: number; - localFamily?: string; - remoteAddress?: string; - remotePort?: number; - remoteFamily?: string; - } - /** - * This class is used to create a TCP or `IPC` server. - * @since v0.1.90 - */ - class Server extends EventEmitter { - constructor(connectionListener?: (socket: Socket) => void); - constructor( - options?: 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; - listen(port?: number, listeningListener?: () => void): this; - listen( - path: string, - backlog?: number, - listeningListener?: () => void, - ): this; - listen(path: string, listeningListener?: () => void): this; - 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 - * 2. connection - * 3. error - * 4. listening - * 5. drop - */ - 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: "drop", listener: (data?: DropArgument) => 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: "drop", data?: DropArgument): 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: "drop", listener: (data?: DropArgument) => 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: "drop", listener: (data?: DropArgument) => 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: "drop", - listener: (data?: DropArgument) => 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: "drop", - listener: (data?: DropArgument) => 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, v14.18.0 - */ - // class BlockList { - // /** - // * Adds a rule to block the given IP address. - // * @since v15.0.0, v14.18.0 - // * @param address An IPv4 or IPv6 address. - // * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - // */ - // addAddress(address: string, type?: IPVersion): void; - // addAddress(address: SocketAddress): void; - // /** - // * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). - // * @since v15.0.0, v14.18.0 - // * @param start The starting IPv4 or IPv6 address in the range. - // * @param end The ending IPv4 or IPv6 address in the range. - // * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - // */ - // addRange(start: string, end: string, type?: IPVersion): void; - // addRange(start: SocketAddress, end: SocketAddress): void; - // /** - // * Adds a rule to block a range of IP addresses specified as a subnet mask. - // * @since v15.0.0, v14.18.0 - // * @param net The network IPv4 or IPv6 address. - // * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. - // * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - // */ - // addSubnet(net: SocketAddress, prefix: number): void; - // addSubnet(net: string, prefix: number, type?: IPVersion): void; - // /** - // * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. - // * - // * ```js - // * const blockList = new net.BlockList(); - // * blockList.addAddress('123.123.123.123'); - // * blockList.addRange('10.0.0.1', '10.0.0.10'); - // * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); - // * - // * console.log(blockList.check('123.123.123.123')); // Prints: true - // * console.log(blockList.check('10.0.0.3')); // Prints: true - // * console.log(blockList.check('222.111.111.222')); // Prints: false - // * - // * // IPv6 notation for IPv4 addresses works: - // * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true - // * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true - // * ``` - // * @since v15.0.0, v14.18.0 - // * @param address The IP address to check - // * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - // */ - // check(address: SocketAddress): boolean; - // check(address: string, type?: IPVersion): boolean; - // } - interface TcpNetConnectOpts - extends TcpSocketConnectOpts, - SocketConstructorOpts { - timeout?: number | 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 a 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; - /** - * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 - * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. - * - * ```js - * net.isIP('::1'); // returns 6 - * net.isIP('127.0.0.1'); // returns 4 - * net.isIP('127.000.000.001'); // returns 0 - * net.isIP('127.0.0.1/24'); // returns 0 - * net.isIP('fhqwhgads'); // returns 0 - * ``` - * @since v0.3.0 - */ - function isIP(input: string): number; - /** - * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no - * leading zeroes. Otherwise, returns `false`. - * - * ```js - * net.isIPv4('127.0.0.1'); // returns true - * net.isIPv4('127.000.000.001'); // returns false - * net.isIPv4('127.0.0.1/24'); // returns false - * net.isIPv4('fhqwhgads'); // returns false - * ``` - * @since v0.3.0 - */ - function isIPv4(input: string): boolean; - /** - * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. - * - * ```js - * net.isIPv6('::1'); // returns true - * net.isIPv6('fhqwhgads'); // returns false - * ``` - * @since v0.3.0 - */ - function isIPv6(input: string): boolean; - // interface SocketAddressInitOptions { - // /** - // * The network address as either an IPv4 or IPv6 string. - // * @default 127.0.0.1 - // */ - // address?: string | undefined; - // /** - // * @default `'ipv4'` - // */ - // family?: IPVersion | undefined; - // /** - // * An IPv6 flow-label used only if `family` is `'ipv6'`. - // * @default 0 - // */ - // flowlabel?: number | undefined; - // /** - // * An IP port. - // * @default 0 - // */ - // port?: number | undefined; - // } - /** - * @since v15.14.0, v14.18.0 - */ - // class SocketAddress { - // constructor(options: SocketAddressInitOptions); - // /** - // * @since v15.14.0, v14.18.0 - // */ - // readonly address: string; - // /** - // * Either \`'ipv4'\` or \`'ipv6'\`. - // * @since v15.14.0, v14.18.0 - // */ - // readonly family: IPVersion; - // /** - // * @since v15.14.0, v14.18.0 - // */ - // readonly port: number; - // /** - // * @since v15.14.0, v14.18.0 - // */ - // readonly flowlabel: number; - // } -} -declare module "node:net" { - export * from "net"; -} diff --git a/packages/bun-types/os.d.ts b/packages/bun-types/os.d.ts deleted file mode 100644 index a357790004..0000000000 --- a/packages/bun-types/os.d.ts +++ /dev/null @@ -1,437 +0,0 @@ -/** - * 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/v18.0.0/lib/os.js) - */ -declare module "os" { - interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - interface NetworkInterfaceBase { - address: string; - netmask: string; - mac: string; - internal: boolean; - cidr: string | null; - } - interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: "IPv4"; - } - interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: "IPv6"; - scopeid: number; - } - interface UserInfo { - username: T; - uid: number; - gid: number; - shell: T; - homedir: T; - } - type NetworkInterfaceInfo = - | NetworkInterfaceInfoIPv4 - | NetworkInterfaceInfoIPv6; - /** - * Returns the host name of the operating system as a string. - */ - 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]`. - */ - function loadavg(): number[]; - /** - * Returns the system uptime in number of seconds. - */ - function uptime(): number; - /** - * Returns the amount of free system memory in bytes as an integer. - */ - function freemem(): number; - /** - * Returns the total amount of system memory in bytes as an integer. - */ - 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. - */ - 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. - */ - 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. - */ - 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' - * } - * ] - * } - * ``` - */ - function networkInterfaces(): 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. - */ - 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`. - */ - function userInfo(options: { encoding: "buffer" }): UserInfo; - function userInfo(options?: { encoding: BufferEncoding }): UserInfo; - type SignalConstants = { - [key in Signals]: number; - }; - namespace constants { - const UV_UDP_REUSEADDR: number; - namespace signals {} - const signals: SignalConstants; - namespace errno { - const E2BIG: number; - const EACCES: number; - const EADDRINUSE: number; - const EADDRNOTAVAIL: number; - const EAFNOSUPPORT: number; - const EAGAIN: number; - const EALREADY: number; - const EBADF: number; - const EBADMSG: number; - const EBUSY: number; - const ECANCELED: number; - const ECHILD: number; - const ECONNABORTED: number; - const ECONNREFUSED: number; - const ECONNRESET: number; - const EDEADLK: number; - const EDESTADDRREQ: number; - const EDOM: number; - const EDQUOT: number; - const EEXIST: number; - const EFAULT: number; - const EFBIG: number; - const EHOSTUNREACH: number; - const EIDRM: number; - const EILSEQ: number; - const EINPROGRESS: number; - const EINTR: number; - const EINVAL: number; - const EIO: number; - const EISCONN: number; - const EISDIR: number; - const ELOOP: number; - const EMFILE: number; - const EMLINK: number; - const EMSGSIZE: number; - const EMULTIHOP: number; - const ENAMETOOLONG: number; - const ENETDOWN: number; - const ENETRESET: number; - const ENETUNREACH: number; - const ENFILE: number; - const ENOBUFS: number; - const ENODATA: number; - const ENODEV: number; - const ENOENT: number; - const ENOEXEC: number; - const ENOLCK: number; - const ENOLINK: number; - const ENOMEM: number; - const ENOMSG: number; - const ENOPROTOOPT: number; - const ENOSPC: number; - const ENOSR: number; - const ENOSTR: number; - const ENOSYS: number; - const ENOTCONN: number; - const ENOTDIR: number; - const ENOTEMPTY: number; - const ENOTSOCK: number; - const ENOTSUP: number; - const ENOTTY: number; - const ENXIO: number; - const EOPNOTSUPP: number; - const EOVERFLOW: number; - const EPERM: number; - const EPIPE: number; - const EPROTO: number; - const EPROTONOSUPPORT: number; - const EPROTOTYPE: number; - const ERANGE: number; - const EROFS: number; - const ESPIPE: number; - const ESRCH: number; - const ESTALE: number; - const ETIME: number; - const ETIMEDOUT: number; - const ETXTBSY: number; - const EWOULDBLOCK: number; - const EXDEV: number; - const WSAEINTR: number; - const WSAEBADF: number; - const WSAEACCES: number; - const WSAEFAULT: number; - const WSAEINVAL: number; - const WSAEMFILE: number; - const WSAEWOULDBLOCK: number; - const WSAEINPROGRESS: number; - const WSAEALREADY: number; - const WSAENOTSOCK: number; - const WSAEDESTADDRREQ: number; - const WSAEMSGSIZE: number; - const WSAEPROTOTYPE: number; - const WSAENOPROTOOPT: number; - const WSAEPROTONOSUPPORT: number; - const WSAESOCKTNOSUPPORT: number; - const WSAEOPNOTSUPP: number; - const WSAEPFNOSUPPORT: number; - const WSAEAFNOSUPPORT: number; - const WSAEADDRINUSE: number; - const WSAEADDRNOTAVAIL: number; - const WSAENETDOWN: number; - const WSAENETUNREACH: number; - const WSAENETRESET: number; - const WSAECONNABORTED: number; - const WSAECONNRESET: number; - const WSAENOBUFS: number; - const WSAEISCONN: number; - const WSAENOTCONN: number; - const WSAESHUTDOWN: number; - const WSAETOOMANYREFS: number; - const WSAETIMEDOUT: number; - const WSAECONNREFUSED: number; - const WSAELOOP: number; - const WSAENAMETOOLONG: number; - const WSAEHOSTDOWN: number; - const WSAEHOSTUNREACH: number; - const WSAENOTEMPTY: number; - const WSAEPROCLIM: number; - const WSAEUSERS: number; - const WSAEDQUOT: number; - const WSAESTALE: number; - const WSAEREMOTE: number; - const WSASYSNOTREADY: number; - const WSAVERNOTSUPPORTED: number; - const WSANOTINITIALISED: number; - const WSAEDISCON: number; - const WSAENOMORE: number; - const WSAECANCELLED: number; - const WSAEINVALIDPROCTABLE: number; - const WSAEINVALIDPROVIDER: number; - const WSAEPROVIDERFAILEDINIT: number; - const WSASYSCALLFAILURE: number; - const WSASERVICE_NOT_FOUND: number; - const WSATYPE_NOT_FOUND: number; - const WSA_E_NO_MORE: number; - const WSA_E_CANCELLED: number; - const WSAEREFUSED: number; - } - namespace priority { - const PRIORITY_LOW: number; - const PRIORITY_BELOW_NORMAL: number; - const PRIORITY_NORMAL: number; - const PRIORITY_ABOVE_NORMAL: number; - const PRIORITY_HIGH: number; - 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'`, and `'x64'`. - * - * The return value is equivalent to `process.arch`. - */ - function arch(): string; - /** - * Returns a string identifying the kernel version. - * - * 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. - */ - function version(): string; - /** - * Returns a string identifying the operating system platform for which - * the Node.js binary was compiled. The value is set at compile time. - * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. - * - * The return value is equivalent to `process.platform`. - */ - function platform(): Platform; - /** - * Returns the operating system's default directory for temporary files as a - * string. - */ - 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. - */ - 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. - * @param [pid=0] The process ID to retrieve scheduling priority for. - */ - function getPriority(pid?: number): number; - /** - * 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`. - * @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; - function setPriority(pid: number, priority: number): void; -} -declare module "node:os" { - export * from "os"; -} diff --git a/packages/bun-types/overrides.d.ts b/packages/bun-types/overrides.d.ts new file mode 100644 index 0000000000..196835e801 --- /dev/null +++ b/packages/bun-types/overrides.d.ts @@ -0,0 +1,77 @@ +declare namespace NodeJS { + type _BunEnv = import("bun").Env; + interface ProcessVersions extends Dict { + bun: string; + } + interface ProcessEnv extends Dict, _BunEnv { + /** + * Can be used to change the default timezone at runtime + */ + NODE_ENV?: string; + } +} + +declare module "fs/promises" { + import { PathLike } from "bun"; + function exists(path: PathLike): Promise; +} + +declare module "tls" { + // eslint-disable-next-line no-duplicate-imports + import { BunFile } from "bun"; + + type BunConnectionOptions = Omit & { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: + | string + | Buffer + | NodeJS.TypedArray + | BunFile + | Array + | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: + | string + | Buffer + | NodeJS.TypedArray + | BunFile + | Array + | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: + | string + | Buffer + | BunFile + | NodeJS.TypedArray + | Array + | undefined; + }; + + function connect( + options: BunConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; +} diff --git a/packages/bun-types/package.json b/packages/bun-types/package.json index 40ce131e46..d41de25ace 100644 --- a/packages/bun-types/package.json +++ b/packages/bun-types/package.json @@ -2,10 +2,15 @@ "name": "bun-types", "repository": "https://github.com/oven-sh/bun", "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/ws": "*", + "undici-types": "~5.26.4" + }, "devDependencies": { - "conditional-type-checks": "^1.0.6", + "@definitelytyped/dtslint": "^0.0.199", + "@definitelytyped/eslint-plugin": "^0.0.197", "prettier": "^2.4.1", - "tsd": "^0.22.0", "typescript": "^5.0.2" }, "private": true, @@ -16,8 +21,5 @@ "test": "tsc", "fmt": "echo $(which prettier) && prettier --write './**/*.{ts,tsx,js,jsx}'" }, - "tsd": { - "directory": "tests" - }, "types": "index.d.ts" } diff --git a/packages/bun-types/path.d.ts b/packages/bun-types/path.d.ts deleted file mode 100644 index 796521b619..0000000000 --- a/packages/bun-types/path.d.ts +++ /dev/null @@ -1,204 +0,0 @@ -/** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: - * - * ```js - * import path from 'path'; - * ``` - */ -declare module "path/posix" { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string | undefined; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string | undefined; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string | undefined; - /** - * The file extension (if any) such as '.html' - */ - ext?: string | undefined; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string | undefined; - } - - /** - * 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. - */ - export function normalize(p: 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. - */ - export function join(...paths: string[]): string; - /** - * 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. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, - * until an absolute path is found. If after using all {from} paths still no absolute path is found, - * 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. - */ - export function resolve(...pathSegments: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(p: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * 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. - */ - export function 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. - */ - export function dirname(p: 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 ext optionally, an extension to remove from the result. - */ - export function basename(p: 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 - * - * @param p the path to evaluate. - */ - export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(p: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pP: 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. - * This method is meaningful only on Windows system. - * On POSIX systems, the method is non-operational and always returns path without modifications. - */ - export function toNamespacedPath(path: string): string; -} - -/** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: - * - * ```js - * import path from 'path'; - * ``` - */ -declare module "path/win32" { - export * from "path/posix"; -} - -/** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: - * - * ```js - * import path from 'path'; - * ``` - */ -declare module "path" { - export * from "path/posix"; - export * as posix from "path/posix"; - export * as win32 from "path/win32"; -} - -/** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: - * - * ```js - * import path from 'path'; - * ``` - */ -declare module "node:path" { - export * from "path"; -} -/** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: - * - * ```js - * import path from 'path'; - * ``` - */ -declare module "node:path/posix" { - export * from "path/posix"; -} -/** - * The `path` module provides utilities for working with file and directory paths. - * It can be accessed using: - * - * ```js - * import path from 'path'; - * ``` - */ -declare module "node:path/win32" { - export * from "path/win32"; -} diff --git a/packages/bun-types/perf_hooks.d.ts b/packages/bun-types/perf_hooks.d.ts deleted file mode 100644 index 587602a265..0000000000 --- a/packages/bun-types/perf_hooks.d.ts +++ /dev/null @@ -1,628 +0,0 @@ -/** - * 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/v18.0.0/lib/perf_hooks.js) - */ -declare module "perf_hooks" { - // import { AsyncResource } from "node:async_hooks"; - // type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http"; - // 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. - // * See perf_hooks.constants for valid values. - // */ - // readonly flags?: number | undefined; - // } - // /** - // * @since v8.5.0 - // */ - // class PerformanceEntry { - // protected constructor(); - // /** - // * The total number of milliseconds elapsed for this entry. This value will not - // * be meaningful for all Performance Entry types. - // * @since v8.5.0 - // */ - // readonly duration: number; - // /** - // * The name of the performance entry. - // * @since v8.5.0 - // */ - // readonly name: string; - // /** - // * The high resolution millisecond timestamp marking the starting time of the - // * Performance Entry. - // * @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. - // toJSON(): any; - // } - // class PerformanceMark extends PerformanceEntry { - // readonly duration: 0; - // readonly entryType: "mark"; - // } - // class PerformanceMeasure extends PerformanceEntry { - // readonly entryType: "measure"; - // } - // /** - // * _This property is an extension by Node.js. It is not available in Web browsers._ - // * - // * Provides timing details for Node.js itself. The constructor of this class - // * is not exposed to users. - // * @since v8.5.0 - // */ - // class PerformanceNodeTiming extends PerformanceEntry { - // /** - // * The high resolution millisecond timestamp at which the Node.js process - // * completed 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 environment was - // * initialized. - // * @since v8.5.0 - // */ - // readonly environment: 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. - // * @since v14.10.0, v12.19.0 - // */ - // readonly idleTime: number; - // /** - // * 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. - // * @since v8.5.0 - // */ - // readonly loopStart: number; - // /** - // * 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. - * If name is provided, removes only the named mark. - * @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', - * and whose performanceEntry.duration is always 0. - * Performance marks are used to mark specific significant moments in the Performance Timeline. - * @param name - * @return The PerformanceMark entry that was created - */ - // mark(name?: string, options?: MarkOptions): PerformanceMark; - /** - * Creates a new PerformanceMeasure entry in the Performance Timeline. - * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', - * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. - * - * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify - * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, - * then startMark is set to timeOrigin by default. - * - * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp - * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. - * @param name - * @param startMark - * @param endMark - * @return The PerformanceMeasure entry that was created - */ - // measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; - // measure(name: string, options: MeasureOptions): PerformanceMeasure; - /** - * 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, 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. - */ - // eventLoopUtilization: EventLoopUtilityFunction; - } - // interface PerformanceObserverEntryList { - // /** - // * 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 - // * * } - // * * ] - // * - // * - // * performance.clearMarks(); - // * performance.clearMeasures(); - // * observer.disconnect(); - // * }); - // * obs.observe({ type: 'mark' }); - // * - // * performance.mark('test'); - // * performance.mark('meow'); - // * ``` - // * @since v8.5.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`. - // * - // * ```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')); // [] - // * - // * performance.clearMarks(); - // * performance.clearMeasures(); - // * observer.disconnect(); - // * }); - // * obs.observe({ entryTypes: ['mark', 'measure'] }); - // * - // * performance.mark('test'); - // * performance.mark('meow'); - // * ``` - // * @since v8.5.0 - // */ - // getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; - // /** - // * 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 - // * * } - // * * ] - // * - // * performance.clearMarks(); - // * performance.clearMeasures(); - // * observer.disconnect(); - // * }); - // * obs.observe({ type: 'mark' }); - // * - // * performance.mark('test'); - // * performance.mark('meow'); - // * ``` - // * @since v8.5.0 - // */ - // getEntriesByType(type: EntryType): PerformanceEntry[]; - // } - // type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; - // class PerformanceObserver extends AsyncResource { - // constructor(callback: PerformanceObserverCallback); - // /** - // * Disconnects the `PerformanceObserver` instance from all notifications. - // * @since v8.5.0 - // */ - // disconnect(): void; - // /** - // * 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 once asynchronously. `list` contains three items. - // * }); - // * obs.observe({ type: 'mark' }); - // * - // * for (let n = 0; n < 3; n++) - // * performance.mark(`test${n}`); - // * ``` - // * @since v8.5.0 - // */ - // observe( - // options: - // | { - // entryTypes: ReadonlyArray; - // 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; - const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; - const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; - 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. - // * Must be greater than zero. - // * @default 10 - // */ - // resolution?: number | undefined; - // } - // interface Histogram { - // /** - // * 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 update interval timer. Returns `true` if the timer was - // * stopped, `false` if it was already stopped. - // * @since v11.10.0 - // */ - // disable(): boolean; - // } - // interface RecordableHistogram extends Histogram { - // /** - // * @since v15.9.0, v14.18.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, v14.18.0 - // */ - // recordDelta(): void; - // /** - // * Adds the values from other to this histogram. - // * @since v17.4.0, v16.14.0 - // * @param other Recordable Histogram to combine with - // */ - // add(other: RecordableHistogram): void; - // } - /** - * _This property is an extension by Node.js. It is not available in Web browsers._ - * - * Creates an `IntervalHistogram` object that samples and reports the event loop - * delay over time. The delays will be reported in nanoseconds. - * - * Using a timer to detect approximate event loop delay works because the - * execution of timers is tied specifically to the lifecycle of the libuv - * event loop. That is, a delay in the loop will cause a delay in the execution - * of the timer, and those delays are specifically what this API is intended to - * detect. - * - * ```js - * const { monitorEventLoopDelay } = require('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, v14.18.0 - */ - // function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; - - // import { performance as _performance } from "perf_hooks"; - // global { - // /** - // * `performance` is a global reference for `require('perf_hooks').performance` - // * https://nodejs.org/api/globals.html#performance - // * @since v16.0.0 - // */ - // var performance: typeof globalThis extends { - // onmessage: any; - // performance: infer T; - // } - // ? T - // : typeof _performance; - // } -} -declare module "node:perf_hooks" { - export * from "perf_hooks"; -} diff --git a/packages/bun-types/punycode.d.ts b/packages/bun-types/punycode.d.ts deleted file mode 100644 index 14628386c0..0000000000 --- a/packages/bun-types/punycode.d.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users - * currently depending on the `punycode` module should switch to using the - * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL - * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. - * - * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It - * can be accessed using: - * - * ```js - * const punycode = require('punycode'); - * ``` - * - * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is - * primarily intended for use in Internationalized Domain Names. Because host - * names in URLs are limited to ASCII characters only, Domain Names that contain - * non-ASCII characters must be converted into ASCII using the Punycode scheme. - * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent - * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. - * - * The `punycode` module provides a simple implementation of the Punycode standard. - * - * The `punycode` module is a third-party dependency used by Node.js and - * made available to developers as a convenience. Fixes or other modifications to - * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. - * @deprecated - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/punycode.js) - */ -declare module "punycode" { - /** - * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only - * characters to the equivalent string of Unicode codepoints. - * - * ```js - * punycode.decode('maana-pta'); // 'mañana' - * punycode.decode('--dqo34k'); // '☃-⌘' - * ``` - */ - function decode(string: string): string; - /** - * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. - * - * ```js - * punycode.encode('mañana'); // 'maana-pta' - * punycode.encode('☃-⌘'); // '--dqo34k' - * ``` - */ - function encode(string: string): string; - /** - * The `punycode.toUnicode()` method converts a string representing a domain name - * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be - * converted. - * - * ```js - * // decode domain names - * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' - * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' - * punycode.toUnicode('example.com'); // 'example.com' - * ``` - */ - function toUnicode(domain: string): string; - /** - * The `punycode.toASCII()` method converts a Unicode string representing an - * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the - * domain name will be converted. Calling `punycode.toASCII()` on a string that - * already only contains ASCII characters will have no effect. - * - * ```js - * // encode domain names - * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' - * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' - * punycode.toASCII('example.com'); // 'example.com' - * ``` - */ - function toASCII(domain: string): string; - /** - * @deprecated - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - const ucs2: ucs2; - interface ucs2 { - /** - * @deprecated - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - decode(string: string): number[]; - /** - * @deprecated - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - encode(codePoints: ReadonlyArray): string; - } - /** - * @deprecated - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - const version: string; -} -declare module "node:punycode" { - export * from "punycode"; -} diff --git a/packages/bun-types/querystring.d.ts b/packages/bun-types/querystring.d.ts deleted file mode 100644 index 429a9ab6af..0000000000 --- a/packages/bun-types/querystring.d.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** - * The `querystring` module provides utilities for parsing and formatting URL - * query strings. It can be accessed using: - * - * ```js - * const querystring = require('querystring'); - * ``` - * - * The `querystring` API is considered Legacy. While it is still maintained, - * new code should use the `URLSearchParams` API instead. - * @deprecated Legacy - * @see [source](https://github.com/nodejs/node/blob/v18.0.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 Dict {} - interface ParsedUrlQueryInput - extends Dict< - | string - | number - | boolean - | ReadonlyArray - | 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 }); - * ``` - * @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 }); - * ``` - * @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(). - */ - const encode: typeof stringify; - /** - * 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. - */ - // FIXME: querystring.escape is typed, but not in the polyfill - // 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. - */ - // FIXME: querystring.unescape is typed, but not in the polyfill - // function unescape(str: string): string; -} -declare module "node:querystring" { - export * from "querystring"; -} diff --git a/packages/bun-types/readline.d.ts b/packages/bun-types/readline.d.ts deleted file mode 100644 index 3125e992b6..0000000000 --- a/packages/bun-types/readline.d.ts +++ /dev/null @@ -1,700 +0,0 @@ -/** - * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. - * - * To use the promise-based APIs: - * - * ```js - * import * as readline from 'node:readline/promises'; - * ``` - * - * To use the callback and sync APIs: - * - * ```js - * import * as readline from 'node:readline'; - * ``` - * - * The following simple example illustrates the basic use of the `readline` module. - * - * ```js - * import * as readline from 'node:readline/promises'; - * import { stdin as input, stdout as output } from 'node:process'; - * - * const rl = readline.createInterface({ input, output }); - * - * const answer = await rl.question('What do you think of Node.js? '); - * - * console.log(`Thank you for your valuable feedback: ${answer}`); - * - * rl.close(); - * ``` - * - * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be - * received on the `input` stream. - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline.js) - */ -declare module "readline" { - import { Readable, Writable } from "node:stream"; - import { Abortable, EventEmitter } from "node:events"; - import * as promises from "node:readline/promises"; - - export { promises }; - export interface Key { - sequence?: string | undefined; - name?: string | undefined; - ctrl?: boolean | undefined; - meta?: boolean | undefined; - shift?: boolean | undefined; - } - /** - * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a - * single `input` `Readable` stream and a single `output` `Writable` stream. - * The `output` stream is used to print prompts for user input that arrives on, - * and is read from, the `input` stream. - * @since v0.1.104 - */ - export class Interface extends EventEmitter { - readonly terminal: boolean; - /** - * 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 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: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor( - input: Readable, - output?: Writable, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ); - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @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 - * line prompts are included in the calculations. - * @since v13.5.0, v12.16.0 - */ - getCursorPos(): CursorPos; - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 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: "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: "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: "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: "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: "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: "history", - listener: (history: string[]) => void, - ): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - export type ReadLine = Interface; // type forwarded for backwards compatibility - export type Completer = (line: string) => CompleterResult; - export type AsyncCompleter = ( - line: string, - callback: (err?: null | Error, result?: CompleterResult) => void, - ) => void; - export type CompleterResult = [string[], string]; - export interface ReadLineOptions { - input: Readable; - output?: Writable | 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 - */ - export function createInterface( - input: Readable, - output?: Writable, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ): Interface; - export function createInterface(options: ReadLineOptions): Interface; - /** - * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. - * - * Optionally, `interface` specifies a `readline.Interface` instance for which - * autocompletion is disabled when copy-pasted input is detected. - * - * If the `stream` is a `TTY`, then it must be in raw mode. - * - * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop - * the `input` from emitting `'keypress'` events. - * - * ```js - * readline.emitKeypressEvents(process.stdin); - * if (process.stdin.isTTY) - * process.stdin.setRawMode(true); - * ``` - * - * ## Example: Tiny CLI - * - * The following example illustrates the use of `readline.Interface` class to - * implement a small command-line interface: - * - * ```js - * const readline = require('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 - */ - export function emitKeypressEvents( - stream: Readable, - readlineInterface?: Interface, - ): void; - export type Direction = -1 | 0 | 1; - export interface CursorPos { - rows: number; - cols: number; - } - /** - * 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`. - */ - export function clearLine( - stream: Writable, - dir: Direction, - callback?: () => void, - ): boolean; - /** - * 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`. - */ - export function clearScreenDown( - stream: Writable, - callback?: () => void, - ): boolean; - /** - * 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`. - */ - export function cursorTo( - stream: Writable, - x: number, - y?: number, - callback?: () => void, - ): boolean; - /** - * 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`. - */ - export function moveCursor( - stream: Writable, - dx: number, - dy: number, - callback?: () => void, - ): boolean; -} -declare module "node:readline" { - export * from "readline"; -} diff --git a/packages/bun-types/readline/promises.d.ts b/packages/bun-types/readline/promises.d.ts deleted file mode 100644 index 5e5df3d3f1..0000000000 --- a/packages/bun-types/readline/promises.d.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. - * - * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) - * @since v17.0.0 - */ -declare module "readline/promises" { - import { Readable, Writable } from "node:stream"; - import { - Interface as _Interface, - ReadLineOptions, - Completer, - AsyncCompleter, - Direction, - } from "node:readline"; - import { Abortable } from "node:events"; - - class Interface extends _Interface { - /** - * 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 readlinePromises.Interface was created with output set to null or undefined the query is not written. - * - * If the question is called after rl.close(), it returns a rejected promise. - * - * Example usage: - * - * ```js - * const answer = await rl.question('What is your favorite food? '); - * console.log(`Oh, so your favorite food is ${answer}`); - * ``` - * - * Using an AbortSignal to cancel a question. - * - * ```js - * const signal = AbortSignal.timeout(10_000); - * - * signal.addEventListener('abort', () => { - * console.log('The food question timed out'); - * }, { once: true }); - * - * const answer = await rl.question('What is your favorite food? ', { signal }); - * console.log(`Oh, so your favorite food is ${answer}`); - * ``` - * - * @since v17.0.0 - * @param query A statement or query to write to output, prepended to the prompt. - */ - question(query: string): Promise; - question(query: string, options: Abortable): Promise; - } - - class Readline { - /** - * @param stream A TTY stream. - */ - constructor(stream: Writable, options?: { autoCommit?: boolean }); - /** - * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. - */ - clearLine(dir: Direction): this; - /** - * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. - */ - clearScreenDown(): this; - /** - * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. - */ - commit(): Promise; - /** - * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. - */ - cursorTo(x: number, y?: number): this; - /** - * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. - */ - moveCursor(dx: number, dy: number): this; - /** - * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. - */ - rollback(): this; - } - - /** - * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. - * - * ```js - * const readlinePromises = require('node:readline/promises'); - * const rl = readlinePromises.createInterface({ - * input: process.stdin, - * output: process.stdout - * }); - * ``` - * - * Once the `readlinePromises.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). - * - * ## Use of the `completer` function - * - * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: - * - * - An Array with matching entries for the completion. - * - The substring that was used for the matching. - * - * For instance: `[[substr1, substr2, ...], originalsubstring]`. - * - * ```js - * function completer(line) { - * const completions = '.help .error .exit .quit .q'.split(' '); - * const hits = completions.filter((c) => c.startsWith(line)); - * // Show all completions if none found - * return [hits.length ? hits : completions, line]; - * } - * ``` - * - * The `completer` function can also returns a `Promise`, or be asynchronous: - * - * ```js - * async function completer(linePartial) { - * await someAsyncWork(); - * return [['123'], linePartial]; - * } - * ``` - */ - function createInterface( - input: Readable, - output?: Writable, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ): Interface; - function createInterface(options: ReadLineOptions): Interface; -} -declare module "node:readline/promises" { - export * from "readline/promises"; -} diff --git a/packages/bun-types/scripts/bundle.ts b/packages/bun-types/scripts/bundle.ts index c1aa00874d..0ac2881005 100644 --- a/packages/bun-types/scripts/bundle.ts +++ b/packages/bun-types/scripts/bundle.ts @@ -10,6 +10,7 @@ const BUN_VERSION = ( Bun.version || process.versions.bun ).replace(/^.*v/, ""); + const folder = resolve(process.argv.at(-1)!); if (folder.endsWith("bundle.ts")) { throw new Error("Pass a folder"); @@ -56,6 +57,11 @@ const packageJSON = { keywords: ["bun", "bun.js", "types"], repository: "https://github.com/oven-sh/bun", homepage: "https://bun.sh", + dependencies: { + "@types/node": "*", + "@types/ws": "*", + "undici-types": "^5.26.4", + }, }; await write( @@ -81,7 +87,6 @@ const tsConfig = { allowSyntheticDefaultImports: true, forceConsistentCasingInFileNames: true, allowJs: true, - types: ["bun-types"], }, }; @@ -96,5 +101,3 @@ await write( ); export {}; - -import "../index"; diff --git a/packages/bun-types/scripts/gpr.ts b/packages/bun-types/scripts/gpr.ts index a17cab4d50..a7af5449f9 100644 --- a/packages/bun-types/scripts/gpr.ts +++ b/packages/bun-types/scripts/gpr.ts @@ -1,5 +1,6 @@ /// import { join } from "path"; +// @ts-ignore import pkg from "../dist/package.json"; const __dirname = new URL(".", import.meta.url).pathname; diff --git a/packages/bun-types/sqlite.d.ts b/packages/bun-types/sqlite.d.ts index 6329103867..133aae0855 100644 --- a/packages/bun-types/sqlite.d.ts +++ b/packages/bun-types/sqlite.d.ts @@ -169,7 +169,7 @@ declare module "bun:sqlite" { sqlQuery: string, ...bindings: ParamsType[] ): void; - /** + /** This is an alias of {@link Database.prototype.run} */ exec( @@ -200,14 +200,11 @@ declare module "bun:sqlite" { * @returns `Statment` instance * * Under the hood, this calls `sqlite3_prepare_v3`. - * */ query( sqlQuery: string, - ): Statement< - ReturnType, - ParamsType extends Array ? ParamsType : [ParamsType] - >; + ): // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type + Statement; /** * Compile a SQL query and return a {@link Statement} object. @@ -228,7 +225,6 @@ declare module "bun:sqlite" { * @returns `Statment` instance * * Under the hood, this calls `sqlite3_prepare_v3`. - * */ prepare< ReturnType, @@ -236,10 +232,8 @@ declare module "bun:sqlite" { >( sqlQuery: string, params?: ParamsType, - ): Statement< - ReturnType, - ParamsType extends Array ? ParamsType : [ParamsType] - >; + ): // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type + Statement; /** * Is the database in a transaction? @@ -316,7 +310,6 @@ declare module "bun:sqlite" { * the SQLite library into the process. * * @param path The path to the SQLite library - * */ static setCustomSQLite(path: string): boolean; @@ -366,7 +359,6 @@ declare module "bun:sqlite" { }; /** - * * Save the database to an in-memory {@link Buffer} object. * * Internally, this calls `sqlite3_serialize`. @@ -377,7 +369,6 @@ declare module "bun:sqlite" { serialize(name?: string): Buffer; /** - * * Load a serialized SQLite3 database * * Internally, this calls `sqlite3_deserialize`. @@ -540,7 +531,6 @@ declare module "bun:sqlite" { * | `Buffer` | `BLOB` | * | `bigint` | `INTEGER` | * | `null` | `NULL` | - * */ get(...params: ParamsType): ReturnType | null; @@ -573,7 +563,6 @@ declare module "bun:sqlite" { * | `Buffer` | `BLOB` | * | `bigint` | `INTEGER` | * | `null` | `NULL` | - * */ run(...params: ParamsType): void; @@ -614,7 +603,6 @@ declare module "bun:sqlite" { * | `Buffer` | `BLOB` | * | `bigint` | `INTEGER` | * | `null` | `NULL` | - * */ values( ...params: ParamsType @@ -646,7 +634,6 @@ declare module "bun:sqlite" { * console.log(stmt.paramsCount); * // => 2 * ``` - * */ readonly paramsCount: number; @@ -695,127 +682,105 @@ declare module "bun:sqlite" { export const constants: { /** * Open the database as read-only (no write operations, no create). - * @value 0x00000001 + * @constant 0x00000001 */ SQLITE_OPEN_READONLY: number; /** * Open the database for reading and writing - * @value 0x00000002 + * @constant 0x00000002 */ SQLITE_OPEN_READWRITE: number; /** * Allow creating a new database - * @value 0x00000004 + * @constant 0x00000004 */ SQLITE_OPEN_CREATE: number; /** - * - * @value 0x00000008 + * @constant 0x00000008 */ SQLITE_OPEN_DELETEONCLOSE: number; /** - * - * @value 0x00000010 + * @constant 0x00000010 */ SQLITE_OPEN_EXCLUSIVE: number; /** - * - * @value 0x00000020 + * @constant 0x00000020 */ SQLITE_OPEN_AUTOPROXY: number; /** - * - * @value 0x00000040 + * @constant 0x00000040 */ SQLITE_OPEN_URI: number; /** - * - * @value 0x00000080 + * @constant 0x00000080 */ SQLITE_OPEN_MEMORY: number; /** - * - * @value 0x00000100 + * @constant 0x00000100 */ SQLITE_OPEN_MAIN_DB: number; /** - * - * @value 0x00000200 + * @constant 0x00000200 */ SQLITE_OPEN_TEMP_DB: number; /** - * - * @value 0x00000400 + * @constant 0x00000400 */ SQLITE_OPEN_TRANSIENT_DB: number; /** - * - * @value 0x00000800 + * @constant 0x00000800 */ SQLITE_OPEN_MAIN_JOURNAL: number; /** - * - * @value 0x00001000 + * @constant 0x00001000 */ SQLITE_OPEN_TEMP_JOURNAL: number; /** - * - * @value 0x00002000 + * @constant 0x00002000 */ SQLITE_OPEN_SUBJOURNAL: number; /** - * - * @value 0x00004000 + * @constant 0x00004000 */ SQLITE_OPEN_SUPER_JOURNAL: number; /** - * - * @value 0x00008000 + * @constant 0x00008000 */ SQLITE_OPEN_NOMUTEX: number; /** - * - * @value 0x00010000 + * @constant 0x00010000 */ SQLITE_OPEN_FULLMUTEX: number; /** - * - * @value 0x00020000 + * @constant 0x00020000 */ SQLITE_OPEN_SHAREDCACHE: number; /** - * - * @value 0x00040000 + * @constant 0x00040000 */ SQLITE_OPEN_PRIVATECACHE: number; /** - * - * @value 0x00080000 + * @constant 0x00080000 */ SQLITE_OPEN_WAL: number; /** - * - * @value 0x01000000 + * @constant 0x01000000 */ SQLITE_OPEN_NOFOLLOW: number; /** - * - * @value 0x02000000 + * @constant 0x02000000 */ SQLITE_OPEN_EXRESCODE: number; /** - * - * @value 0x01 + * @constant 0x01 */ SQLITE_PREPARE_PERSISTENT: number; /** - * - * @value 0x02 + * @constant 0x02 */ SQLITE_PREPARE_NORMALIZE: number; /** - * - * @value 0x04 + * @constant 0x04 */ SQLITE_PREPARE_NO_VTAB: number; }; @@ -831,7 +796,6 @@ declare module "bun:sqlite" { * * If you need to use it directly for some reason, please let us know because * that probably points to a deficiency in this API. - * */ export var native: any; diff --git a/packages/bun-types/stream.d.ts b/packages/bun-types/stream.d.ts deleted file mode 100644 index 71705e4dd6..0000000000 --- a/packages/bun-types/stream.d.ts +++ /dev/null @@ -1,1470 +0,0 @@ -/** - * 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/v18.0.0/lib/stream.js) - */ -declare module "stream" { - import { EventEmitter, Abortable } from "node:events"; - class internal extends EventEmitter { - pipe( - destination: T, - options?: { - end?: boolean | undefined; - }, - ): T; - } - namespace internal { - class Stream extends internal { - constructor(opts?: ReadableOptions); - } - interface StreamOptions extends Abortable { - emitClose?: boolean | undefined; - highWaterMark?: number | undefined; - objectMode?: boolean | undefined; - 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; - } - class Readable extends Stream { - forEach( - callbackfn: ( - value: any, - key: number, - parent: ReadableStream, - ) => void, - thisArg?: any, - ): void; - /** - * A utility method for creating a `Readable` from a web `ReadableStream`. - * @since v17.0.0 - * @experimental - */ - static fromWeb( - readableStream: ReadableStream, - options?: Pick< - ReadableOptions, - "encoding" | "highWaterMark" | "objectMode" | "signal" - >, - ): Readable; - /** - * A utility method for creating a web `ReadableStream` from a `Readable`. - * @since v17.0.0 - * @experimental - */ - static toWeb(streamReadable: Readable): ReadableStream; - /** - * Returns whether the stream has been read from or cancelled. - */ - static isDisturbed(stream: Readable | ReadableStream): boolean; - /** - * Returns whether the stream was destroyed or errored before emitting `'end'`. - * @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'`. - */ - readable: boolean; - /** - * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. - */ - readonly readableEncoding: BufferEncoding | null; - /** - * Becomes `true` when `'end'` event is emitted. - */ - readonly readableEnded: boolean; - /** - * This property reflects the current state of a `Readable` stream as described - * in the `Three states` section. - */ - readonly readableFlowing: boolean | null; - /** - * Returns the value of `highWaterMark` passed when creating this `Readable`. - */ - 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`. - */ - readonly readableLength: number; - /** - * Getter for the property `objectMode` of a given `Readable` stream. - */ - readonly readableObjectMode: boolean; - /** - * Is `true` after `readable.destroy()` has been called. - */ - destroyed: boolean; - constructor(opts?: ReadableOptions); - _construct?(callback: (error?: Error | null) => void): void; - _read(size: number): void; - /** - * The `readable.read()` method reads data out of the internal buffer and - * returns it. If no data is available to be read, `null` is returned. By default, - * the data is 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. - * @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); - * }); - * ``` - * @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. - */ - 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. - */ - 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 - * ``` - */ - 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); - * ``` - * @param destination Optional specific stream to unpipe - */ - unpipe(destination?: 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.includes('\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); - * return; - * } - * // 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. - * @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; - /** - * 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. - * }); - * ``` - * @param stream An "old style" readable stream - */ - wrap(stream: 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()`. - * @param error Error which will be passed as payload in `'error'` event - */ - destroy(error?: Error): this; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. error - * 5. pause - * 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: 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: 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: 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: 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: 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: 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: string | symbol, - listener: (...args: any[]) => void, - ): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - interface WritableOptions extends StreamOptions { - decodeStrings?: boolean | undefined; - defaultEncoding?: BufferEncoding | 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; - final?(this: Writable, callback: (error?: Error | null) => void): void; - } - class Writable extends Stream { - /** - * A utility method for creating a `Writable` from a web `WritableStream`. - * @since v17.0.0 - * @experimental - */ - static fromWeb( - writableStream: WritableStream, - options?: Pick< - WritableOptions, - "decodeStrings" | "highWaterMark" | "objectMode" | "signal" - >, - ): Writable; - /** - * A utility method for creating a web `WritableStream` from a `Writable`. - * @since v17.0.0 - * @experimental - */ - static toWeb(streamWritable: Writable): WritableStream; - /** - * Is `true` if it is safe to call `writable.write()`, which means - * the stream has not been destroyed, errored or ended. - */ - 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. - */ - readonly writableEnded: boolean; - /** - * Is set to `true` immediately before the `'finish'` event is emitted. - */ - readonly writableFinished: boolean; - /** - * Return the value of `highWaterMark` passed when creating this `Writable`. - */ - 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`. - */ - readonly writableLength: number; - /** - * Getter for the property `objectMode` of a given `Writable` stream. - */ - readonly writableObjectMode: boolean; - /** - * Number of times `writable.uncork()` needs to be - * called in order to fully uncork the stream. - */ - readonly writableCorked: number; - /** - * Is `true` after `writable.destroy()` has been called. - */ - destroyed: boolean; - constructor(opts?: WritableOptions); - - /** - * Hide internal methods from the public API. - */ - // _write( - // 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; - - /** - * 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. - * Once `write()` returns false, do not write more chunks - * 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. - * @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: W, - callback?: (error: Error | null | undefined) => void, - ): boolean; - write( - chunk: W, - encoding: BufferEncoding, - callback?: (error: Error | null | undefined) => void, - ): boolean; - /** - * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. - * @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! - * ``` - * @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()`. - */ - 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, defer calls to `writable.uncork()` 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()`. - */ - 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()`. - * @param error Optional, an error to emit with `'error'` event. - */ - destroy(error?: Error): this; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 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: 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: 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: 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: 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: 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: 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: string | symbol, - listener: (...args: any[]) => void, - ): this; - } - interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean | undefined; - readableObjectMode?: boolean | undefined; - writableObjectMode?: boolean | undefined; - 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; - final?(this: Duplex, callback: (error?: Error | null) => void): void; - destroy?( - this: Duplex, - error: Error | null, - callback: (error: Error | null) => void, - ): void; - } - /** - * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. - * - * Examples of `Duplex` streams include: - * - * * `TCP sockets` - * * `zlib streams` - * * `crypto streams` - */ - type Duplex = Readable & - Writable & { - /** - * 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; - }; - interface DuplexConstructor { - new (opts?: DuplexOptions): Duplex; - /** - * 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 - */ - from( - src: - | Stream - | Blob - | ArrayBuffer - | string - | Iterable - | AsyncIterable - | AsyncGeneratorFunction - | Promise - | Object, - ): Duplex; - fromWeb( - pair: { - readable: ReadableStream; - writable: WritableStream; - }, - options: DuplexOptions, - ): Duplex; - toWeb(stream: Duplex): { - readable: ReadableStream; - writable: WritableStream; - }; - } - var Duplex: DuplexConstructor; - 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; - 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; - } - /** - * 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; - * } - * } - * })(); - * ``` - * @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(); - * // ... - * }); - * ``` - * @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: ReadableStream | WritableStream | ReadWriteStream, - options: FinishedOptions, - callback: (err?: ErrnoException | null) => void, - ): () => void; - function finished( - stream: ReadableStream | WritableStream | ReadWriteStream, - callback: (err?: ErrnoException | null) => void, - ): () => void; - namespace finished { - function __promisify__( - stream: ReadableStream | WritableStream | ReadWriteStream, - options?: FinishedOptions, - ): Promise; - } - type PipelineSourceFunction = () => Iterable | AsyncIterable; - type PipelineSource = - | Iterable - | AsyncIterable - | ReadableStream - | PipelineSourceFunction; - type PipelineTransform, U> = - | 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< - S extends PipelineTransformSource, - P, - > = S extends PipelineTransformSource - ? - | WritableStream - | PipelineDestinationIterableFunction - | PipelineDestinationPromiseFunction - : never; - type PipelineCallback> = - S extends PipelineDestinationPromiseFunction - ? (err: ErrnoException | null, value: P) => void - : (err: 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. If the last - * stream is readable, dangling event listeners will be removed so that the last - * stream can be consumed later. - * - * `stream.pipeline()` closes all the streams when an error is raised. - * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior - * once it would destroy the socket without sending the expected response. - * See the example below: - * - * ```js - * const fs = require('fs'); - * const http = require('http'); - * const { pipeline } = require('stream'); - * - * const server = http.createServer((req, res) => { - * const fileStream = fs.createReadStream('./fileNotExist.txt'); - * pipeline(fileStream, res, (err) => { - * if (err) { - * console.log(err); // No such file - * // this message can't be sent once `pipeline` already destroyed the socket - * return res.end('error!!!'); - * } - * }); - * }); - * ``` - * @param callback Called when the pipeline is fully done. - */ - function pipeline< - A extends PipelineSource, - B extends PipelineDestination, - >( - source: A, - destination: B, - callback?: PipelineCallback, - ): B extends WritableStream ? B : WritableStream; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - destination: B, - callback?: PipelineCallback, - ): B extends WritableStream ? B : WritableStream; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - destination: B, - callback?: PipelineCallback, - ): B extends WritableStream ? B : 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 WritableStream ? B : 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 WritableStream ? B : WritableStream; - function pipeline( - streams: ReadonlyArray, - callback?: (err: ErrnoException | null) => void, - ): WritableStream; - function pipeline( - stream1: ReadableStream, - stream2: ReadWriteStream | WritableStream, - ...streams: Array< - | ReadWriteStream - | WritableStream - | ((err: ErrnoException | null) => void) - > - ): WritableStream; - namespace pipeline { - function __promisify__< - A extends PipelineSource, - B extends PipelineDestination, - >( - source: A, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__< - A extends PipelineSource, - T1 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__< - A extends PipelineSource, - 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< - ReadableStream | WritableStream | ReadWriteStream - >, - options?: PipelineOptions, - ): Promise; - function __promisify__( - stream1: ReadableStream, - stream2: ReadWriteStream | WritableStream, - ...streams: Array - ): Promise; - } - interface Pipe { - close(): void; - hasRef(): boolean; - ref(): void; - unref(): void; - } - - /** - * Returns whether the stream has encountered an error. - */ - function isErrored( - stream: Readable | Writable | ReadableStream | WritableStream, - ): boolean; - - /** - * Returns whether the stream is readable. - */ - function isReadable(stream: Readable | ReadableStream): boolean; - } - export = internal; -} -declare module "node:stream" { - import stream = require("stream"); - export = stream; -} diff --git a/packages/bun-types/string_decoder.d.ts b/packages/bun-types/string_decoder.d.ts deleted file mode 100644 index b4d507fac0..0000000000 --- a/packages/bun-types/string_decoder.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 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/v18.0.0/lib/string_decoder.js) - */ -declare module "string_decoder" { - import { ArrayBufferView } from "bun"; - 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()`. - * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. - */ - write(buffer: ArrayBufferView): 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. - * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. - */ - end(buffer?: ArrayBufferView): string; - } -} -declare module "node:string_decoder" { - export * from "string_decoder"; -} diff --git a/packages/bun-types/supports-color.d.ts b/packages/bun-types/supports-color.d.ts deleted file mode 100644 index 7f4323b021..0000000000 --- a/packages/bun-types/supports-color.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -declare module "supports-color" { - export interface Options { - /** - Whether `process.argv` should be sniffed for `--color` and `--no-color` flags. - @default true - */ - readonly sniffFlags?: boolean; - } - - /** - Levels: - - `0` - All colors disabled. - - `1` - Basic 16 colors support. - - `2` - ANSI 256 colors support. - - `3` - Truecolor 16 million colors support. - */ - export type ColorSupportLevel = 0 | 1 | 2 | 3; - - /** - Detect whether the terminal supports color. - */ - export interface ColorSupport { - /** - The color level. - */ - level: ColorSupportLevel; - - /** - Whether basic 16 colors are supported. - */ - hasBasic: boolean; - - /** - Whether ANSI 256 colors are supported. - */ - has256: boolean; - - /** - Whether Truecolor 16 million colors are supported. - */ - has16m: boolean; - } - - export type ColorInfo = ColorSupport | false; - - export const supportsColor: { - stdout: ColorInfo; - stderr: ColorInfo; - }; - - export const stdout: ColorInfo; - export const stderr: ColorInfo; - - export default supportsColor; -} diff --git a/packages/bun-types/bun-test.d.ts b/packages/bun-types/test.d.ts similarity index 97% rename from packages/bun-types/bun-test.d.ts rename to packages/bun-types/test.d.ts index b6070fcb20..76f1e1b88f 100644 --- a/packages/bun-types/bun-test.d.ts +++ b/packages/bun-types/test.d.ts @@ -168,7 +168,7 @@ declare module "bun:test" { * @param label the label for the tests * @param fn the function that defines the tests */ - export type Describe = { + export interface Describe { (label: string, fn: () => void): void; /** * Skips all other tests, except this group of tests. @@ -212,27 +212,27 @@ declare module "bun:test" { */ each>( - table: ReadonlyArray, + table: readonly T[], ): ( label: string, fn: (...args: [...T]) => void | Promise, options?: number | TestOptions, ) => void; - each>( - table: ReadonlyArray, + each( + table: readonly T[], ): ( label: string, fn: (...args: Readonly) => void | Promise, options?: number | TestOptions, ) => void; each( - table: Array, + table: T[], ): ( label: string, fn: (...args: T[]) => void | Promise, options?: number | TestOptions, ) => void; - }; + } /** * Describes a group of related tests. * @@ -320,7 +320,7 @@ declare module "bun:test" { | (() => void | Promise) | ((done: (err?: unknown) => void) => void), ): void; - export type TestOptions = { + export interface TestOptions { /** * Sets the timeout for the test in milliseconds. * @@ -344,7 +344,7 @@ declare module "bun:test" { * @default 0 */ repeats?: number; - }; + } /** * Runs a test. * @@ -366,7 +366,7 @@ declare module "bun:test" { * @param fn the test function * @param options the test timeout or options */ - export type Test = { + export interface Test { ( label: string, fn: @@ -464,27 +464,27 @@ declare module "bun:test" { * @param table Array of Arrays with the arguments that are passed into the test fn for each row. */ each>( - table: ReadonlyArray, + table: readonly T[], ): ( label: string, fn: (...args: [...T]) => void | Promise, options?: number | TestOptions, ) => void; - each>( - table: ReadonlyArray, + each( + table: readonly T[], ): ( label: string, fn: (...args: Readonly) => void | Promise, options?: number | TestOptions, ) => void; each( - table: Array, + table: T[], ): ( label: string, fn: (...args: T[]) => void | Promise, options?: number | TestOptions, ) => void; - }; + } /** * Runs a test. * @@ -989,7 +989,7 @@ declare module "bun:test" { * @param value the expected property value, if provided */ toHaveProperty( - keyPath: string | number | (string | number)[], + keyPath: string | number | Array, value?: unknown, ): void; /** @@ -1406,15 +1406,15 @@ declare module "bun:test" { /** * Ensure that a mock function is called with specific arguments. */ - toHaveBeenCalledWith(...expected: Array): void; + toHaveBeenCalledWith(...expected: unknown[]): void; /** * Ensure that a mock function is called with specific arguments for the last call. */ - toHaveBeenLastCalledWith(...expected: Array): void; + toHaveBeenLastCalledWith(...expected: unknown[]): void; /** * Ensure that a mock function is called with specific arguments for the nth call. */ - toHaveBeenNthCalledWith(n: number, ...expected: Array): void; + toHaveBeenNthCalledWith(n: number, ...expected: unknown[]): void; } /** @@ -1456,7 +1456,7 @@ declare module "bun:test" { this: TesterContext, a: any, b: any, - customTesters: Array, + customTesters: Tester[], ) => boolean | undefined; export type EqualsFunction = ( @@ -1533,9 +1533,9 @@ declare namespace JestMock { * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ - export type ClassLike = { + export interface ClassLike { new (...args: any): any; - }; + } export type ConstructorLikeKeys = keyof { [K in keyof T as Required[K] extends ClassLike ? K : never]: T[K]; @@ -1637,7 +1637,7 @@ declare namespace JestMock { | MockFunctionResultReturn | MockFunctionResultThrow; - type MockFunctionResultIncomplete = { + interface MockFunctionResultIncomplete { type: "incomplete"; /** * Result of a single call to a mock function that has not yet completed. @@ -1645,25 +1645,25 @@ declare namespace JestMock { * or from within a function that was called by the mock. */ value: undefined; - }; + } - type MockFunctionResultReturn = { + interface MockFunctionResultReturn { type: "return"; /** * Result of a single call to a mock function that returned. */ value: ReturnType; - }; + } - type MockFunctionResultThrow = { + interface MockFunctionResultThrow { type: "throw"; /** * Result of a single call to a mock function that threw. */ value: unknown; - }; + } - type MockFunctionState = { + interface MockFunctionState { /** * List of the call arguments of all calls that have been made to the mock. */ @@ -1680,7 +1680,7 @@ declare namespace JestMock { * List of the call order indexes of the mock. Jest is indexing the order of * invocations of all mocks in a test file. The index is starting with `1`. */ - invocationCallOrder: Array; + invocationCallOrder: number[]; /** * List of the call arguments of the last call that was made to the mock. * If the function was not called, it will return `undefined`. @@ -1690,7 +1690,7 @@ declare namespace JestMock { * List of the results of all calls that have been made to the mock. */ results: Array>; - }; + } export interface MockInstance { _isMockFunction: true; @@ -1847,7 +1847,7 @@ declare namespace JestMock { replaceValue(value: T): this; } - export const replaceProperty: < + export function replaceProperty< T extends object, K_2 extends Exclude< keyof T, @@ -1861,11 +1861,7 @@ declare namespace JestMock { } >, V extends T[K_2], - >( - object: T, - propertyKey: K_2, - value: V, - ) => Replaced; + >(object: T, propertyKey: K_2, value: V): Replaced; export type ResolveType = ReturnType extends PromiseLike ? U : never; @@ -1937,11 +1933,11 @@ declare namespace JestMock { ): V_1 extends ClassLike | FunctionLike ? Spied : never; }; - export type UnknownClass = { - new (...args: Array): unknown; - }; + export interface UnknownClass { + new (...args: unknown[]): unknown; + } - export type UnknownFunction = (...args: Array) => unknown; + export type UnknownFunction = (...args: unknown[]) => unknown; export {}; } diff --git a/packages/bun-types/tests/array-buffer.test-d.ts b/packages/bun-types/test/array-buffer.test.ts similarity index 100% rename from packages/bun-types/tests/array-buffer.test-d.ts rename to packages/bun-types/test/array-buffer.test.ts diff --git a/packages/bun-types/tests/array.test-d.ts b/packages/bun-types/test/array.test.ts similarity index 70% rename from packages/bun-types/tests/array.test-d.ts rename to packages/bun-types/test/array.test.ts index f7ba9a6513..4b979e9e2a 100644 --- a/packages/bun-types/tests/array.test-d.ts +++ b/packages/bun-types/test/array.test.ts @@ -3,7 +3,7 @@ async function* listReleases() { const response = await fetch( `https://api.github.com/repos/oven-sh/bun/releases?page=${page}`, ); - const releases: { data: string }[] = await response.json(); + const releases = (await response.json()) as Array<{ data: string }>; if (!releases.length) { break; } @@ -13,4 +13,6 @@ async function* listReleases() { } } -export const releases = await Array.fromAsync(listReleases()); +await Array.fromAsync(listReleases()); + +export {}; diff --git a/packages/bun-types/tests/broadcast.test-d.ts b/packages/bun-types/test/broadcast.test.ts similarity index 67% rename from packages/bun-types/tests/broadcast.test-d.ts rename to packages/bun-types/test/broadcast.test.ts index ea5f8cb054..1d853f7fec 100644 --- a/packages/bun-types/tests/broadcast.test-d.ts +++ b/packages/bun-types/test/broadcast.test.ts @@ -2,7 +2,8 @@ const channel = new BroadcastChannel("my-channel"); const message = { hello: "world" }; channel.onmessage = event => { - console.log(event.data); // { hello: "world" } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.log((event as any).data); // { hello: "world" } }; channel.postMessage(message); diff --git a/packages/bun-types/tests/bun.test-d.ts b/packages/bun-types/test/bun.test.ts similarity index 75% rename from packages/bun-types/tests/bun.test-d.ts rename to packages/bun-types/test/bun.test.ts index cd5a40ecaf..ae642ff6f1 100644 --- a/packages/bun-types/tests/bun.test-d.ts +++ b/packages/bun-types/test/bun.test.ts @@ -1,5 +1,5 @@ import { BunFile, BunPlugin, FileBlob } from "bun"; -import * as tsd from "tsd"; +import * as tsd from "./utilities.test"; { const _plugin: BunPlugin = { name: "asdf", @@ -8,15 +8,18 @@ import * as tsd from "tsd"; _plugin; } { + // tslint:disable-next-line:no-void-expression const arg = Bun.plugin({ name: "arg", setup() {}, }); + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type tsd.expectType(arg); } { + // tslint:disable-next-line:no-void-expression const arg = Bun.plugin({ name: "arg", async setup() {}, @@ -44,3 +47,5 @@ import * as tsd from "tsd"; { Bun.TOML.parse("asdf = asdf"); } + +DOMException; diff --git a/packages/bun-types/test/console.test.ts b/packages/bun-types/test/console.test.ts new file mode 100644 index 0000000000..779bbab198 --- /dev/null +++ b/packages/bun-types/test/console.test.ts @@ -0,0 +1,23 @@ +import c2 from "console"; +import c1 from "node:console"; + +c1.log(); +c2.log(); + +async () => { + // tslint:disable-next-line:await-promise + for await (const line of c1) { + console.log("Received:", line); + } + + // tslint:disable-next-line:await-promise + for await (const line of c2) { + console.log("Received:", line); + } + // tslint:disable-next-line:await-promise + for await (const line of console) { + console.log("Received:", line); + } + + return null; +}; diff --git a/packages/bun-types/test/crypto.test.ts b/packages/bun-types/test/crypto.test.ts new file mode 100644 index 0000000000..6081bb023c --- /dev/null +++ b/packages/bun-types/test/crypto.test.ts @@ -0,0 +1,3 @@ +import { webcrypto } from "crypto"; + +webcrypto.CryptoKey; diff --git a/packages/bun-types/tests/diag.test-d.ts b/packages/bun-types/test/diag.test.ts similarity index 100% rename from packages/bun-types/tests/diag.test-d.ts rename to packages/bun-types/test/diag.test.ts diff --git a/packages/bun-types/tests/dns.test-d.ts b/packages/bun-types/test/dns.test.ts similarity index 100% rename from packages/bun-types/tests/dns.test-d.ts rename to packages/bun-types/test/dns.test.ts diff --git a/packages/bun-types/test/dom.test.ts b/packages/bun-types/test/dom.test.ts new file mode 100644 index 0000000000..c3d8a43836 --- /dev/null +++ b/packages/bun-types/test/dom.test.ts @@ -0,0 +1,25 @@ +import { INSPECT_MAX_BYTES } from "buffer"; + +INSPECT_MAX_BYTES; + +{ + new Blob([]); +} +{ + new MessagePort(); +} +{ + new MessageChannel(); +} +{ + new BroadcastChannel("zxgdfg"); +} + +{ + new Response("asdf"); +} +{ + Response.json({ asdf: "asdf" }).ok; + const r = Response.json({ hello: "world" }); + r.body; +} diff --git a/packages/bun-types/tests/env.test-d.ts b/packages/bun-types/test/env.test.ts similarity index 69% rename from packages/bun-types/tests/env.test-d.ts rename to packages/bun-types/test/env.test.ts index d78fccc5b9..f9b1d53be6 100644 --- a/packages/bun-types/tests/env.test-d.ts +++ b/packages/bun-types/test/env.test.ts @@ -1,12 +1,14 @@ -import { expectType } from "tsd"; +import { expectType } from "./utilities.test"; declare module "bun" { - export interface Env { + interface Env { FOO: "FOO"; } } +expectType<"FOO">(process.env.FOO); declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace namespace NodeJS { interface ProcessEnv { BAR: "BAR"; @@ -14,7 +16,6 @@ declare global { } } -expectType<"FOO">(process.env.FOO); expectType<"BAR">(process.env.BAR); process.env.FOO; diff --git a/packages/bun-types/test/events.test.ts b/packages/bun-types/test/events.test.ts new file mode 100644 index 0000000000..d774a4b619 --- /dev/null +++ b/packages/bun-types/test/events.test.ts @@ -0,0 +1,20 @@ +import { EventEmitter } from "events"; +import { expectType } from "./utilities.test"; + +// eslint-disable-next-line @definitelytyped/no-single-element-tuple-type +// EventEmitter< +// const e1 = new EventEmitter<{ a: [string] }>(); + +// e1.on("a", (arg) => { +// expectType(arg); +// }); +// // @ts-expect-error +// e1.on("qwer", (_) => {}); + +const e2 = new EventEmitter(); +e2.on("qwer", (_: any) => { + _; +}); +e2.on("asdf", arg => { + expectType(arg); +}); diff --git a/packages/bun-types/test/ffi.test.ts b/packages/bun-types/test/ffi.test.ts new file mode 100644 index 0000000000..c84fc86d38 --- /dev/null +++ b/packages/bun-types/test/ffi.test.ts @@ -0,0 +1,184 @@ +import { CString, dlopen, FFIType, Pointer, read, suffix } from "bun:ffi"; +import * as tsd from "./utilities.test"; + +// `suffix` is either "dylib", "so", or "dll" depending on the platform +// you don't have to use "suffix", it's just there for convenience +const path = `libsqlite3.${suffix}`; + +const lib = dlopen( + path, // a library name or file path + { + sqlite3_libversion: { + // no arguments, returns a string + args: [], + returns: FFIType.cstring, + }, + add: { + args: [FFIType.i32, FFIType.i32], + returns: FFIType.i32, + }, + ptr_type: { + args: [FFIType.pointer], + returns: FFIType.pointer, + }, + fn_type: { + args: [FFIType.function], + returns: FFIType.function, + }, + allArgs: { + args: [ + FFIType.char, // string + FFIType.int8_t, + FFIType.i8, + FFIType.uint8_t, + FFIType.u8, + FFIType.int16_t, + FFIType.i16, + FFIType.uint16_t, + FFIType.u16, + FFIType.int32_t, + FFIType.i32, + FFIType.int, + FFIType.uint32_t, + FFIType.u32, + FFIType.int64_t, + FFIType.i64, + FFIType.uint64_t, + FFIType.u64, + FFIType.double, + FFIType.f64, + FFIType.float, + FFIType.f32, + FFIType.bool, + FFIType.ptr, + FFIType.pointer, + FFIType.void, + FFIType.cstring, + FFIType.i64_fast, + FFIType.u64_fast, + ], + returns: FFIType.void, + }, + }, +); + +tsd.expectType(lib.symbols.sqlite3_libversion()); +tsd.expectType(lib.symbols.add(1, 2)); + +tsd.expectType(lib.symbols.ptr_type(0)); + +tsd.expectType(lib.symbols.fn_type(0)); + +function _arg( + ...params: [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + boolean, + Pointer, + Pointer, + // tslint:disable-next-line: void-return + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + void, + CString, + number | bigint, + number | bigint, + ] +) { + console.log("asdf"); +} +_arg; + +type libParams = Parameters<(typeof lib)["symbols"]["allArgs"]>; +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); +tsd.expectTypeEquals(true); + +// tslint:disable-next-line:no-object-literal-type-assertion +const as_const_test = { + sqlite3_libversion: { + args: [], + returns: FFIType.cstring, + }, + multi_args: { + args: [FFIType.i32, FFIType.f32], + returns: FFIType.void, + }, + no_returns: { + args: [FFIType.i32], + }, + no_args: { + returns: FFIType.i32, + }, +} as const; + +const lib2 = dlopen(path, as_const_test); + +tsd.expectType(lib2.symbols.sqlite3_libversion()); +// tslint:disable-next-line:no-void-expression +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type +tsd.expectType(lib2.symbols.multi_args(1, 2)); +tsd.expectTypeEquals< + ReturnType<(typeof lib2)["symbols"]["no_returns"]>, + undefined +>(true); +tsd.expectTypeEquals, []>(true); + +tsd.expectType(read.u8(0)); +tsd.expectType(read.u8(0, 0)); +tsd.expectType(read.i8(0, 0)); +tsd.expectType(read.u16(0, 0)); +tsd.expectType(read.i16(0, 0)); +tsd.expectType(read.u32(0, 0)); +tsd.expectType(read.i32(0, 0)); +tsd.expectType(read.u64(0, 0)); +tsd.expectType(read.i64(0, 0)); +tsd.expectType(read.f32(0, 0)); +tsd.expectType(read.f64(0, 0)); +tsd.expectType(read.ptr(0, 0)); +tsd.expectType(read.intptr(0, 0)); diff --git a/packages/bun-types/tests/fs.test-d.ts b/packages/bun-types/test/fs.test.ts similarity index 63% rename from packages/bun-types/tests/fs.test-d.ts rename to packages/bun-types/test/fs.test.ts index a752889df8..ce78e13f84 100644 --- a/packages/bun-types/tests/fs.test-d.ts +++ b/packages/bun-types/test/fs.test.ts @@ -1,7 +1,10 @@ -import { watch } from "node:fs"; -import * as tsd from "tsd"; +import { constants, watch, readdir } from "node:fs"; + +constants.O_APPEND; + import * as fs from "fs"; import { exists } from "fs/promises"; +import * as tsd from "./utilities.test"; tsd.expectType>(exists("/etc/passwd")); tsd.expectType>(fs.promises.exists("/etc/passwd")); @@ -14,4 +17,6 @@ watch(".", (eventType, filename) => { } }); -Bun.file("sdf").exists(); +await Bun.file("sdf").exists(); + +readdir(".", { recursive: true }, (err, files) => {}); diff --git a/packages/bun-types/tests/fsrouter.test-d.ts b/packages/bun-types/test/fsrouter.test.ts similarity index 81% rename from packages/bun-types/tests/fsrouter.test-d.ts rename to packages/bun-types/test/fsrouter.test.ts index 05556f60a6..1a1b997556 100644 --- a/packages/bun-types/tests/fsrouter.test-d.ts +++ b/packages/bun-types/test/fsrouter.test.ts @@ -1,8 +1,8 @@ import { FileSystemRouter } from "bun"; -import { expectType } from "tsd"; +import { expectType } from "./utilities.test"; const router = new FileSystemRouter({ - dir: import.meta.dir + "/pages", + dir: "/pages", style: "nextjs", }); diff --git a/packages/bun-types/test/globals.test.ts b/packages/bun-types/test/globals.test.ts new file mode 100644 index 0000000000..13caf97bcc --- /dev/null +++ b/packages/bun-types/test/globals.test.ts @@ -0,0 +1,318 @@ +import { ZlibCompressionOptions } from "bun"; +import * as fs from "fs"; +import * as fsPromises from "fs/promises"; +import { expectAssignable, expectType } from "./utilities.test"; + +// FileBlob +expectType>(Bun.file("index.test-d.ts").stream()); +expectType>(Bun.file("index.test-d.ts").arrayBuffer()); +expectType>(Bun.file("index.test-d.ts").text()); + +expectType(Bun.file("index.test-d.ts").size); +expectType(Bun.file("index.test-d.ts").type); + +// Hash +expectType(new Bun.MD4().update("test").digest("hex")); +expectType(new Bun.MD5().update("test").digest("hex")); +expectType(new Bun.SHA1().update("test").digest("hex")); +expectType(new Bun.SHA224().update("test").digest("hex")); +expectType(new Bun.SHA256().update("test").digest("hex")); +expectType(new Bun.SHA384().update("test").digest("hex")); +expectType(new Bun.SHA512().update("test").digest("hex")); +expectType(new Bun.SHA512_256().update("test").digest("hex")); + +// Zlib Functions +expectType(Bun.deflateSync(new Uint8Array(128))); +expectType(Bun.gzipSync(new Uint8Array(128))); +expectType( + Bun.deflateSync(new Uint8Array(128), { + level: -1, + memLevel: 8, + strategy: 0, + windowBits: 15, + }), +); +expectType( + Bun.gzipSync(new Uint8Array(128), { level: 9, memLevel: 6, windowBits: 27 }), +); +expectType(Bun.inflateSync(new Uint8Array(64))); // Pretend this is DEFLATE compressed data +expectType(Bun.gunzipSync(new Uint8Array(64))); // Pretend this is GZIP compressed data +expectAssignable({ windowBits: -11 }); + +// Other +expectType>(Bun.write("test.json", "lol")); +expectType>(Bun.write("test.json", new ArrayBuffer(32))); +expectType(Bun.pathToFileURL("/foo/bar.txt")); +expectType(Bun.fileURLToPath(new URL("file:///foo/bar.txt"))); + +// Testing ../fs.d.ts +expectType( + fs.readFileSync("./index.d.ts", { encoding: "utf-8" }).toString(), +); +expectType(fs.existsSync("./index.d.ts")); +// tslint:disable-next-line:no-void-expression +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type +expectType(fs.accessSync("./index.d.ts")); +// tslint:disable-next-line:no-void-expression +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type +expectType(fs.appendFileSync("./index.d.ts", "test")); +// tslint:disable-next-line:no-void-expression +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type +expectType(fs.mkdirSync("./index.d.ts")); + +// Testing ^promises.d.ts +expectType( + (await fsPromises.readFile("./index.d.ts", { encoding: "utf-8" })).toString(), +); +expectType>(fsPromises.access("./index.d.ts")); +expectType>(fsPromises.appendFile("./index.d.ts", "test")); +expectType>(fsPromises.mkdir("./index.d.ts")); + +Bun.env; + +Bun.version; + +setImmediate; +clearImmediate; +setInterval; +clearInterval; +setTimeout; +clearTimeout; + +const arg = new AbortSignal(); +arg; + +const e = new CustomEvent("asdf"); +console.log(e); + +exports; +module.exports; + +global.AbortController; +global.Bun; + +const er = new DOMException(); +er.name; +er.HIERARCHY_REQUEST_ERR; + +new Request(new Request("https://example.com"), {}); +new Request("", { method: "POST" }); + +Bun.sleepSync(1); // sleep for 1 ms (not recommended) +await Bun.sleep(1); // sleep for 1 ms (recommended) + +Blob; +WebSocket; +Request; +Response; +Headers; +FormData; +URL; +URLSearchParams; +ReadableStream; +WritableStream; +TransformStream; +ByteLengthQueuingStrategy; +CountQueuingStrategy; +TextEncoder; +TextDecoder; +ReadableStreamDefaultReader; +// ReadableStreamBYOBReader; +ReadableStreamDefaultController; +// ReadableByteStreamController; +WritableStreamDefaultWriter; + +function stuff(arg: Blob): any; +function stuff(arg: WebSocket): any; +function stuff(arg: Request): any; +function stuff(arg: Response): any; +function stuff(arg: Headers): any; +function stuff(arg: FormData): any; +function stuff(arg: URL): any; +function stuff(arg: URLSearchParams): any; +function stuff(arg: ReadableStream): any; +function stuff(arg: WritableStream): any; +function stuff(arg: TransformStream): any; +function stuff(arg: ByteLengthQueuingStrategy): any; +function stuff(arg: CountQueuingStrategy): any; +function stuff(arg: TextEncoder): any; +function stuff(arg: TextDecoder): any; +function stuff(arg: ReadableStreamDefaultReader): any; +function stuff(arg: ReadableStreamDefaultController): any; +function stuff(arg: WritableStreamDefaultWriter): any; +function stuff(arg: any) { + return "asfd"; +} + +stuff("asdf" as any as Blob); + +new ReadableStream(); +new WritableStream(); +new Worker("asdfasdf"); +new File([{} as Blob], "asdf"); +new Crypto(); +new ShadowRealm(); +new ErrorEvent("asdf"); +new CloseEvent("asdf"); +new MessageEvent("asdf"); +new CustomEvent("asdf"); +// new Loader(); + +const readableStream = new ReadableStream(); +const writableStream = new WritableStream(); + +{ + const a = new ByteLengthQueuingStrategy({ highWaterMark: 0 }); + a.highWaterMark; +} +{ + const a = new ReadableStreamDefaultController(); + a.close(); +} +{ + const a = new ReadableStreamDefaultReader(readableStream); + await a.cancel(); +} +{ + const a = new WritableStreamDefaultController(); + a.error(); +} +{ + const a = new WritableStreamDefaultWriter(writableStream); + await a.close(); +} +{ + const a = new TransformStream(); + a.readable; +} +{ + const a = new TransformStreamDefaultController(); + a.enqueue("asdf"); +} +{ + const a = new CountQueuingStrategy({ highWaterMark: 0 }); + a.highWaterMark; +} +{ + const a = new DOMException(); + a.DATA_CLONE_ERR; +} +{ + const a = new SubtleCrypto(); + await a.decrypt("asdf", new CryptoKey(), new Uint8Array()); +} +{ + const a = new CryptoKey(); + a.algorithm; +} +{ + const a = new BuildError(); + a.level; +} +{ + const a = new ResolveError(); + a.level; +} +{ + const a = new EventSource("asdf"); + a.CLOSED; +} +{ + const a = new AbortController(); + a; +} +{ + const a = new AbortSignal(); + a.aborted; +} +{ + const a = new Request("asdf"); + await a.json(); + a.cache; +} +{ + const a = new Response(); + await a.text(); + a.ok; +} +{ + const a = new FormData(); + a.delete("asdf"); +} +{ + const a = new Headers(); + a.append("asdf", "asdf"); +} +{ + const a = new EventTarget(); + a.dispatchEvent(new Event("asdf")); +} +{ + const a = new Event("asdf"); + a.bubbles; + a.composedPath()[0]; +} +{ + const a = new Blob(); + a.size; +} +{ + const a = new File(["asdf"], "stuff.txt "); + a.name; +} +{ + performance.now(); +} +{ + const a = new URL("asdf"); + a.host; + a.href; +} +{ + const a = new URLSearchParams(); + a; +} +{ + const a = new TextDecoder(); + a.decode(new Uint8Array()); +} +{ + const a = new TextEncoder(); + a.encode("asdf"); +} +{ + const a = new BroadcastChannel("stuff"); + a.close(); +} +{ + const a = new MessageChannel(); + a.port1; +} +{ + const a = new MessagePort(); + a.close(); +} + +{ + var a!: RequestInit; + a.mode; + a.credentials; +} +{ + var b!: ResponseInit; + b.status; +} +{ + const ws = new WebSocket("ws://www.host.com/path"); + ws.send("asdf"); +} + +atob("asf"); +btoa("asdf"); + +setInterval(() => {}, 1000); +setTimeout(() => {}, 1000); +clearInterval(1); +clearTimeout(1); +setImmediate(() => {}); +clearImmediate(1); diff --git a/packages/bun-types/test/hashing.test.ts b/packages/bun-types/test/hashing.test.ts new file mode 100644 index 0000000000..553e0f1ff0 --- /dev/null +++ b/packages/bun-types/test/hashing.test.ts @@ -0,0 +1 @@ +Bun.hash.wyhash("asdf", 1234n); diff --git a/packages/bun-types/test/headers.test.ts b/packages/bun-types/test/headers.test.ts new file mode 100644 index 0000000000..470cc99ec8 --- /dev/null +++ b/packages/bun-types/test/headers.test.ts @@ -0,0 +1,9 @@ +const headers = new Headers(); +headers.append("Set-Cookie", "a=1"); +headers.append("Set-Cookie", "b=1; Secure"); + +// both of these are no longer in the types +// because Headers is declared with `class` in @types/node +// and I can't find a way to add them to the prototype +// console.log(headers.getAll("Set-Cookie")); // ["a=1", "b=1; Secure"] +// console.log(headers.toJSON()); // { "set-cookie": "a=1, b=1; Secure" } diff --git a/packages/bun-types/tests/http.test-d.ts b/packages/bun-types/test/http.test.ts similarity index 100% rename from packages/bun-types/tests/http.test-d.ts rename to packages/bun-types/test/http.test.ts diff --git a/packages/bun-types/test/index.test.ts b/packages/bun-types/test/index.test.ts new file mode 100644 index 0000000000..b450749119 --- /dev/null +++ b/packages/bun-types/test/index.test.ts @@ -0,0 +1,2 @@ +Bun.spawn(["echo", '"hi"']); +performance; diff --git a/packages/bun-types/tests/jsc.test-d.ts b/packages/bun-types/test/jsc.test.ts similarity index 62% rename from packages/bun-types/tests/jsc.test-d.ts rename to packages/bun-types/test/jsc.test.ts index 34e134338f..c1a531f115 100644 --- a/packages/bun-types/tests/jsc.test-d.ts +++ b/packages/bun-types/test/jsc.test.ts @@ -1,7 +1,8 @@ -import { serialize, deserialize } from "bun:jsc"; import { deepEquals } from "bun"; +import { deserialize, serialize } from "bun:jsc"; const obj = { a: 1, b: 2 }; const buffer = serialize(obj); +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const clone = deserialize(buffer); if (deepEquals(obj, clone)) { diff --git a/packages/bun-types/tests/mocks.test-d.ts b/packages/bun-types/test/mocks.test.ts similarity index 88% rename from packages/bun-types/tests/mocks.test-d.ts rename to packages/bun-types/test/mocks.test.ts index 9bb8a90703..8c89174335 100644 --- a/packages/bun-types/tests/mocks.test-d.ts +++ b/packages/bun-types/test/mocks.test.ts @@ -1,5 +1,5 @@ -import { expectType } from "tsd"; -import { mock, jest } from "bun:test"; +import { jest, mock } from "bun:test"; +import { expectType } from "./utilities.test"; const mock1 = mock((arg: string) => { return arg.length; diff --git a/packages/bun-types/tests/net.test-d.ts b/packages/bun-types/test/net.test.ts similarity index 100% rename from packages/bun-types/tests/net.test-d.ts rename to packages/bun-types/test/net.test.ts diff --git a/packages/bun-types/test/perf_hooks.test.ts b/packages/bun-types/test/perf_hooks.test.ts new file mode 100644 index 0000000000..271cea04f9 --- /dev/null +++ b/packages/bun-types/test/perf_hooks.test.ts @@ -0,0 +1,7 @@ +import { performance as _performance } from "node:perf_hooks"; + +performance.now(); +performance.timeOrigin; + +_performance.now(); +_performance.timeOrigin; diff --git a/packages/bun-types/tests/process.test-d.ts b/packages/bun-types/test/process.test.ts similarity index 90% rename from packages/bun-types/tests/process.test-d.ts rename to packages/bun-types/test/process.test.ts index 0aa0f9b27d..6ea7cf043d 100644 --- a/packages/bun-types/tests/process.test-d.ts +++ b/packages/bun-types/test/process.test.ts @@ -14,20 +14,17 @@ process.on("exit", code => { }); process.kill(123, "SIGTERM"); -process.getegid(); -process.geteuid(); -process.getgid(); -process.getgroups(); -process.getuid(); +process.getegid!(); +process.geteuid!(); +process.getgid!(); +process.getgroups!(); +process.getuid!(); process.once("SIGINT", () => { console.log("Interrupt from keyboard"); }); -process.reallyExit(); - -process.assert(false, "PleAsE don't Use THIs It IS dEpReCATED"); - +// commented methods are not yet implemented console.log(process.allowedNodeEnvironmentFlags); // console.log(process.channel); // console.log(process.connected); @@ -49,3 +46,5 @@ console.log(process.memoryUsage()); // console.log(process.resourceUsage); // console.log(process.setSourceMapsEnabled()); // console.log(process.send); +process.reallyExit(); +process.assert(false, "PleAsE don't Use THIs It IS dEpReCATED"); diff --git a/packages/bun-types/tests/readline.test-d.ts b/packages/bun-types/test/readline.test.ts similarity index 61% rename from packages/bun-types/tests/readline.test-d.ts rename to packages/bun-types/test/readline.test.ts index b1eecdce0b..967d9b06d5 100644 --- a/packages/bun-types/tests/readline.test-d.ts +++ b/packages/bun-types/test/readline.test.ts @@ -5,5 +5,6 @@ const rl = readline.createInterface({ output: process.stdout, terminal: true, }); -const answer = await rl.question("What is your age?\n"); -console.log("Your age is: " + answer); +await rl.question("What is your age?\n").then(answer => { + console.log("Your age is: " + answer); +}); diff --git a/packages/bun-types/tests/serve.test-d.ts b/packages/bun-types/test/serve.test.ts similarity index 92% rename from packages/bun-types/tests/serve.test-d.ts rename to packages/bun-types/test/serve.test.ts index 09796506b7..1ddd23a0c6 100644 --- a/packages/bun-types/tests/serve.test-d.ts +++ b/packages/bun-types/test/serve.test.ts @@ -25,19 +25,18 @@ Bun.serve({ // Upgrade to a ServerWebSocket if we can // This automatically checks for the `Sec-WebSocket-Key` header // meaning you don't have to check headers, you can just call `upgrade()` - if (server.upgrade(req)) + if (server.upgrade(req)) { // When upgrading, we return undefined since we don't want to send a Response return; + } return new Response("Regular HTTP response"); }, }); -type User = { +Bun.serve<{ name: string; -}; - -Bun.serve({ +}>({ fetch(req, server) { const url = new URL(req.url); if (url.pathname === "/chat") { @@ -50,8 +49,9 @@ Bun.serve({ "Set-Cookie": "name=" + new URL(req.url).searchParams.get("name"), }, }) - ) + ) { return; + } } return new Response("Expected a websocket connection", { status: 400 }); @@ -64,7 +64,7 @@ Bun.serve({ }, message(ws, message) { - ws.publish("the-group-chat", `${ws.data.name}: ${message}`); + ws.publish("the-group-chat", `${ws.data.name}: ${message.toString()}`); }, close(ws, code, reason) { @@ -79,31 +79,12 @@ Bun.serve({ }, }); -Bun.serve({ - fetch(req, server) { - server.upgrade(req); - }, - - websocket: { - open(ws) { - console.log("WebSocket opened"); - ws.subscribe("test-channel"); - }, - - message(ws, message) { - ws.publish("test-channel", `${message}`); - }, - - perMessageDeflate: true, - }, -}); - Bun.serve({ fetch(req) { throw new Error("woops!"); }, error(error) { - return new Response(`

${error}\n${error.stack}
`, { + return new Response(`
${error.message}\n${error.stack}
`, { headers: { "Content-Type": "text/html", }, @@ -159,6 +140,22 @@ Bun.serve({ tls: {}, }); +Bun.serve({ + fetch(req, server) { + server.upgrade(req); + }, + websocket: { + open(ws) { + console.log("WebSocket opened"); + ws.subscribe("test-channel"); + }, + + message(ws, message) { + ws.publish("test-channel", `${message.toString()}`); + }, + perMessageDeflate: true, + }, +}); // Bun.serve({ // unix: "/tmp/bun.sock", // // @ts-expect-error diff --git a/packages/bun-types/tests/spawn.test-d.ts b/packages/bun-types/test/spawn.test.ts similarity index 86% rename from packages/bun-types/tests/spawn.test-d.ts rename to packages/bun-types/test/spawn.test.ts index 14a753d04e..35cc3516ea 100644 --- a/packages/bun-types/tests/spawn.test-d.ts +++ b/packages/bun-types/test/spawn.test.ts @@ -6,9 +6,14 @@ import { SyncSubprocess, WritableSubprocess, } from "bun"; -import * as tsd from "tsd"; +import * as tsd from "./utilities.test"; Bun.spawn(["echo", "hello"]); + +function depromise(_promise: Promise): T { + return "asdf" as any as T; +} + { const proc = Bun.spawn(["echo", "hello"], { cwd: "./path/to/subdir", // specify a working direcory @@ -27,12 +32,14 @@ Bun.spawn(["echo", "hello"]); { const proc = Bun.spawn(["cat"], { - stdin: await fetch( - "https://raw.githubusercontent.com/oven-sh/bun/main/examples/hashing.js", + stdin: depromise( + fetch( + "https://raw.githubusercontent.com/oven-sh/bun/main/examples/hashing.js", + ), ), }); - const text = await new Response(proc.stdout).text(); + const text = depromise(new Response(proc.stdout).text()); console.log(text); // "const input = "hello world".repeat(400); ..." } @@ -47,17 +54,22 @@ Bun.spawn(["echo", "hello"]); // enqueue binary data const enc = new TextEncoder(); proc.stdin.write(enc.encode(" world!")); + enc.encodeInto(" world!", {} as any as Uint8Array); + // Bun-specific overloads + // these fail when lib.dom.d.ts is present + enc.encodeInto(" world!", new Uint32Array(124)); + enc.encodeInto(" world!", {} as any as DataView); // send buffered data - proc.stdin.flush(); + await proc.stdin.flush(); // close the input stream - proc.stdin.end(); + await proc.stdin.end(); } { const proc = Bun.spawn(["echo", "hello"]); - const text = await new Response(proc.stdout).text(); + const text = depromise(new Response(proc.stdout).text()); console.log(text); // => "hello" } diff --git a/packages/bun-types/tests/sqlite.test-d.ts b/packages/bun-types/test/sqlite.test.ts similarity index 70% rename from packages/bun-types/tests/sqlite.test-d.ts rename to packages/bun-types/test/sqlite.test.ts index b1c2e3ddb6..c094eab8c9 100644 --- a/packages/bun-types/tests/sqlite.test-d.ts +++ b/packages/bun-types/test/sqlite.test.ts @@ -1,5 +1,5 @@ import { Database } from "bun:sqlite"; -import { expectType } from "tsd"; +import { expectType } from "./utilities.test"; const db = new Database(":memory:"); const query1 = db.query< @@ -14,15 +14,20 @@ const query2 = db.query< >("select ?1 as name, ?2 as dob"); const allResults = query2.all("Shaq", 50); // => {name: string; dob:string}[] const getResults = query2.get("Shaq", 50); // => {name: string; dob:string}[] + +// tslint:disable-next-line:no-void-expression const runResults = query2.run("Shaq", 50); // => {name: string; dob:string}[] -expectType<{ name: string; dob: number }[]>(allResults); +expectType>(allResults); expectType<{ name: string; dob: number } | null>(getResults); +// tslint:disable-next-line:invalid-void +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type expectType(runResults); const query3 = db.prepare< { name: string; dob: number }, // return type first + // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type [{ $id: string }] >("select name, dob from users where id = $id"); const allResults3 = query3.all({ $id: "asdf" }); -expectType<{ name: string; dob: number }[]>(allResults3); +expectType>(allResults3); diff --git a/packages/bun-types/tests/stdio.test-d.ts b/packages/bun-types/test/stdio.test.ts similarity index 100% rename from packages/bun-types/tests/stdio.test-d.ts rename to packages/bun-types/test/stdio.test.ts diff --git a/packages/bun-types/tests/streams.test-d.ts b/packages/bun-types/test/streams.test.ts similarity index 70% rename from packages/bun-types/tests/streams.test-d.ts rename to packages/bun-types/test/streams.test.ts index b894dd9fef..50c6fdeb65 100644 --- a/packages/bun-types/tests/streams.test-d.ts +++ b/packages/bun-types/test/streams.test.ts @@ -6,10 +6,14 @@ new ReadableStream({ }, }); +// this will have type errors when lib.dom.d.ts is present +// afaik this isn't fixable new ReadableStream({ type: "direct", pull(controller) { + // eslint-disable-next-line controller.write("hello"); + // eslint-disable-next-line controller.write("world"); controller.close(); }, diff --git a/packages/bun-types/tests/tcp.test-d.ts b/packages/bun-types/test/tcp.test.ts similarity index 98% rename from packages/bun-types/tests/tcp.test-d.ts rename to packages/bun-types/test/tcp.test.ts index 92c765ff6b..fe1b66a648 100644 --- a/packages/bun-types/tests/tcp.test-d.ts +++ b/packages/bun-types/test/tcp.test.ts @@ -131,7 +131,7 @@ const listener = Bun.listen({ unix: "asdf", }); -listener.data!.arg = "asdf"; +listener.data.arg = "asdf"; // @ts-expect-error arg is string listener.data.arg = 234; diff --git a/packages/bun-types/tests/test.test-d.ts b/packages/bun-types/test/test.test.ts similarity index 97% rename from packages/bun-types/tests/test.test-d.ts rename to packages/bun-types/test/test.test.ts index b385c3051e..ef5c02f9ed 100644 --- a/packages/bun-types/tests/test.test-d.ts +++ b/packages/bun-types/test/test.test.ts @@ -1,14 +1,14 @@ import { - test, - expect, - describe, - beforeAll, afterAll, - beforeEach, afterEach, + beforeAll, + beforeEach, + describe, + expect, spyOn, + test, } from "bun:test"; -import { expectType } from "tsd"; +import { expectType } from "./utilities.test"; const spy = spyOn(console, "log"); expectType(spy.mock.calls); @@ -19,8 +19,10 @@ for (const hook of hooks) { hook(() => { // ... }); + // eslint-disable-next-line hook(async () => { // ... + return; }); hook((done: (err?: unknown) => void) => { done(); diff --git a/packages/bun-types/tests/tls.test-d.ts b/packages/bun-types/test/tls.test.ts similarity index 100% rename from packages/bun-types/tests/tls.test-d.ts rename to packages/bun-types/test/tls.test.ts diff --git a/packages/bun-types/test/toml.test.ts b/packages/bun-types/test/toml.test.ts new file mode 100644 index 0000000000..9c872488df --- /dev/null +++ b/packages/bun-types/test/toml.test.ts @@ -0,0 +1,4 @@ +import data from "./bunfig.toml"; +import { expectType } from "./utilities.test"; + +expectType(data); diff --git a/packages/bun-types/tests/tty.test-d.ts b/packages/bun-types/test/tty.test.ts similarity index 100% rename from packages/bun-types/tests/tty.test-d.ts rename to packages/bun-types/test/tty.test.ts diff --git a/packages/bun-types/tests/util.test-d.ts b/packages/bun-types/test/util.test.ts similarity index 100% rename from packages/bun-types/tests/util.test-d.ts rename to packages/bun-types/test/util.test.ts diff --git a/packages/bun-types/test/utilities.test.ts b/packages/bun-types/test/utilities.test.ts new file mode 100644 index 0000000000..c542e1a78a --- /dev/null +++ b/packages/bun-types/test/utilities.test.ts @@ -0,0 +1,10 @@ +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export declare const expectType: (expression: T) => void; +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export declare const expectAssignable: (expression: T) => void; +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export declare const expectNotAssignable: (expression: any) => void; +// eslint-disable-next-line @definitelytyped/no-unnecessary-generics +export declare const expectTypeEquals: ( + expression: T extends S ? (S extends T ? true : false) : false, +) => void; diff --git a/packages/bun-types/test/wasm.test.ts b/packages/bun-types/test/wasm.test.ts new file mode 100644 index 0000000000..3b8785ec73 --- /dev/null +++ b/packages/bun-types/test/wasm.test.ts @@ -0,0 +1,42 @@ +async () => { + // Fetch and compile a WebAssembly module + const response = await fetch("module.wasm"); + const buffer = await response.arrayBuffer(); + const module = await WebAssembly.compile(buffer); + + // Create a WebAssembly Memory object + const memory = new WebAssembly.Memory({ initial: 1 }); + + // Create a WebAssembly Table object + const table = new WebAssembly.Table({ initial: 1, element: "anyfunc" }); + + // Instantiate the WebAssembly module + const instance = await WebAssembly.instantiate(module, { + js: { + log: (arg: any) => console.log("Logging from WASM:", arg), + tableFunc: () => console.log("Table function called"), + }, + env: { + memory: memory, + table: table, + }, + }); + + // Exported WebAssembly functions + const { exportedFunction } = instance.exports; + exportedFunction; + + // Call an exported WebAssembly function + // exportedFunction(); + + // Interact with WebAssembly memory + const uint8Array = new Uint8Array(memory.buffer); + uint8Array[0] = 1; // Modify memory + + // Use the WebAssembly Table + table.set(0, instance.exports.exportedTableFunction); + // eslint-disable-next-line + table.get(0)(); // Call a function stored in the table + + // Additional operations with instance, memory, and table can be performed here +}; diff --git a/packages/bun-types/tests/worker.test-d.ts b/packages/bun-types/test/worker.test.ts similarity index 62% rename from packages/bun-types/tests/worker.test-d.ts rename to packages/bun-types/test/worker.test.ts index dc457ccaa2..335f2652a9 100644 --- a/packages/bun-types/tests/worker.test-d.ts +++ b/packages/bun-types/test/worker.test.ts @@ -1,5 +1,5 @@ import { Worker as NodeWorker } from "node:worker_threads"; -import * as tsd from "tsd"; +import * as tsd from "./utilities.test"; const webWorker = new Worker("./worker.js"); @@ -12,6 +12,16 @@ webWorker.addEventListener("error", event => { webWorker.addEventListener("messageerror", event => { tsd.expectType(event); }); +webWorker.onmessage = ev => "asdf"; +webWorker.onmessageerror = ev => "asdf"; +webWorker.postMessage("asdf", []); +webWorker.terminate(); +webWorker.addEventListener("close", () => {}); +webWorker.removeEventListener("sadf", () => {}); +// these methods don't exist if lib.dom.d.ts is present +webWorker.ref(); +webWorker.unref(); +webWorker.threadId; const nodeWorker = new NodeWorker("./worker.ts"); nodeWorker.on("message", event => { @@ -19,7 +29,7 @@ nodeWorker.on("message", event => { }); nodeWorker.postMessage("Hello from main thread!"); -const workerURL = new URL("worker.ts", import.meta.url).href; +const workerURL = new URL("worker.ts", "/path/to/").href; const _worker2 = new Worker(workerURL); nodeWorker.postMessage("hello"); @@ -34,17 +44,18 @@ postMessage({ hello: "world" }); nodeWorker.postMessage({ hello: "world" }); // ...some time later -nodeWorker.terminate(); + +await nodeWorker.terminate(); // Bun.pathToFileURL -const _worker3 = new Worker(new URL("worker.ts", import.meta.url).href, { +const _worker3 = new Worker(new URL("worker.ts", "/path/to/").href, { ref: true, smol: true, - credentials: "", + credentials: "same-origin", name: "a name", env: { envValue: "hello", }, }); -export { nodeWorker as worker, _worker2, _worker3 }; +export { _worker2, _worker3, nodeWorker as worker }; diff --git a/packages/bun-types/tests/ws.test-d.ts b/packages/bun-types/test/ws.test.ts similarity index 100% rename from packages/bun-types/tests/ws.test-d.ts rename to packages/bun-types/test/ws.test.ts diff --git a/packages/bun-types/tests/console.test-d.ts b/packages/bun-types/tests/console.test-d.ts deleted file mode 100644 index 9392b7e9f9..0000000000 --- a/packages/bun-types/tests/console.test-d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as c1 from "node:console"; -import * as c2 from "console"; - -c1.log(); -c2.log(); - -for await (const line of c1) { - console.log("Received:", line); -} - -for await (const line of c2) { - console.log("Received:", line); -} - -for await (const line of console) { - console.log("Received:", line); -} - -export {}; diff --git a/packages/bun-types/tests/events.test-d.ts b/packages/bun-types/tests/events.test-d.ts deleted file mode 100644 index e68a77ce52..0000000000 --- a/packages/bun-types/tests/events.test-d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { EventEmitter } from "events"; -import { expectType } from "tsd"; - -const e1 = new EventEmitter<{ - a: [string]; -}>(); - -e1.on("a", arg => { - expectType(arg); -}); -// @ts-expect-error -e1.on("qwer", _ => {}); - -const e2 = new EventEmitter(); -e2.on("qwer", _ => {}); -e2.on("asdf", arg => { - expectType(arg); -}); diff --git a/packages/bun-types/tests/exports.d.ts b/packages/bun-types/tests/exports.d.ts deleted file mode 100644 index 45e52ec7d0..0000000000 --- a/packages/bun-types/tests/exports.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// - -export * as fs from "fs"; -export * as fsPromises from "fs/promises"; -export default Bun; diff --git a/packages/bun-types/tests/ffi.test-d.ts b/packages/bun-types/tests/ffi.test-d.ts deleted file mode 100644 index 36136d287e..0000000000 --- a/packages/bun-types/tests/ffi.test-d.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { - dlopen, - FFIType, - suffix, - CString, - Pointer, - JSCallback, - read, - // FFIFunction, - // ConvertFns, - // Narrow, -} from "bun:ffi"; -import * as tsd from "tsd"; -import * as tc from "conditional-type-checks"; - -// `suffix` is either "dylib", "so", or "dll" depending on the platform -// you don't have to use "suffix", it's just there for convenience -const path = `libsqlite3.${suffix}`; - -const lib = dlopen( - path, // a library name or file path - { - sqlite3_libversion: { - // no arguments, returns a string - args: [], - returns: FFIType.cstring, - }, - add: { - args: [FFIType.i32, FFIType.i32], - returns: FFIType.i32, - }, - ptr_type: { - args: [FFIType.pointer], - returns: FFIType.pointer, - }, - fn_type: { - args: [FFIType.function], - returns: FFIType.function, - }, - allArgs: { - args: [ - FFIType.char, // string - FFIType.int8_t, - FFIType.i8, - FFIType.uint8_t, - FFIType.u8, - FFIType.int16_t, - FFIType.i16, - FFIType.uint16_t, - FFIType.u16, - FFIType.int32_t, - FFIType.i32, - FFIType.int, - FFIType.uint32_t, - FFIType.u32, - FFIType.int64_t, - FFIType.i64, - FFIType.uint64_t, - FFIType.u64, - FFIType.double, - FFIType.f64, - FFIType.float, - FFIType.f32, - FFIType.bool, - FFIType.ptr, - FFIType.pointer, - FFIType.void, - FFIType.cstring, - FFIType.i64_fast, - FFIType.u64_fast, - ], - returns: FFIType.void, - }, - }, -); - -tsd.expectType(lib.symbols.sqlite3_libversion()); -tsd.expectType(lib.symbols.add(1, 2)); - -tsd.expectType(lib.symbols.ptr_type(0)); -tc.assert< - tc.IsExact< - (typeof lib)["symbols"]["ptr_type"], - TypedArray | Pointer | CString - > ->; - -tsd.expectType(lib.symbols.fn_type(0)); -tc.assert>; - -tc.assert< - tc.IsExact< - (typeof lib)["symbols"]["allArgs"], - [ - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - number, - boolean, - Pointer, - Pointer, - void, - CString, - number | bigint, - number | bigint, - ] - > ->; - -const as_const_test = { - sqlite3_libversion: { - args: [], - returns: FFIType.cstring, - }, - multi_args: { - args: [FFIType.i32, FFIType.f32], - returns: FFIType.void, - }, - no_returns: { - args: [FFIType.i32], - }, - no_args: { - returns: FFIType.i32, - }, -} as const; - -const lib2 = dlopen(path, as_const_test); - -tsd.expectType(lib2.symbols.sqlite3_libversion()); -tsd.expectType(lib2.symbols.multi_args(1, 2)); -tc.assert, void>>; -tc.assert, []>>; - -tsd.expectType(read.u8(0)); -tsd.expectType(read.u8(0, 0)); -tsd.expectType(read.i8(0, 0)); -tsd.expectType(read.u16(0, 0)); -tsd.expectType(read.i16(0, 0)); -tsd.expectType(read.u32(0, 0)); -tsd.expectType(read.i32(0, 0)); -tsd.expectType(read.u64(0, 0)); -tsd.expectType(read.i64(0, 0)); -tsd.expectType(read.f32(0, 0)); -tsd.expectType(read.f64(0, 0)); -tsd.expectType(read.ptr(0, 0)); -tsd.expectType(read.intptr(0, 0)); diff --git a/packages/bun-types/tests/globals.test-d.ts b/packages/bun-types/tests/globals.test-d.ts deleted file mode 100644 index a5441f2012..0000000000 --- a/packages/bun-types/tests/globals.test-d.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { ZlibCompressionOptions } from "bun"; -import { expectAssignable, expectType } from "tsd"; -import Bun, { fs, fsPromises } from "./exports"; - -// FileBlob -expectType>(Bun.file("index.test-d.ts").stream()); -expectType>(Bun.file("index.test-d.ts").arrayBuffer()); -expectType>(Bun.file("index.test-d.ts").text()); - -expectType(Bun.file("index.test-d.ts").size); -expectType(Bun.file("index.test-d.ts").type); - -// Hash -expectType(new Bun.MD4().update("test").digest("hex")); -expectType(new Bun.MD5().update("test").digest("hex")); -expectType(new Bun.SHA1().update("test").digest("hex")); -expectType(new Bun.SHA224().update("test").digest("hex")); -expectType(new Bun.SHA256().update("test").digest("hex")); -expectType(new Bun.SHA384().update("test").digest("hex")); -expectType(new Bun.SHA512().update("test").digest("hex")); -expectType(new Bun.SHA512_256().update("test").digest("hex")); - -// Zlib Functions -expectType(Bun.deflateSync(new Uint8Array(128))); -expectType(Bun.gzipSync(new Uint8Array(128))); -expectType( - Bun.deflateSync(new Uint8Array(128), { - level: -1, - memLevel: 8, - strategy: 0, - windowBits: 15, - }), -); -expectType( - Bun.gzipSync(new Uint8Array(128), { level: 9, memLevel: 6, windowBits: 27 }), -); -expectType(Bun.inflateSync(new Uint8Array(64))); // Pretend this is DEFLATE compressed data -expectType(Bun.gunzipSync(new Uint8Array(64))); // Pretend this is GZIP compressed data -expectAssignable({ windowBits: -11 }); - -// Other -expectType>(Bun.write("test.json", "lol")); -expectType>(Bun.write("test.json", new ArrayBuffer(32))); -expectType(Bun.pathToFileURL("/foo/bar.txt")); -expectType(Bun.fileURLToPath(new URL("file:///foo/bar.txt"))); - -// Testing ../fs.d.ts -expectType( - fs.readFileSync("./index.d.ts", { encoding: "utf-8" }).toString(), -); -expectType(fs.existsSync("./index.d.ts")); -expectType(fs.accessSync("./index.d.ts")); -expectType(fs.appendFileSync("./index.d.ts", "test")); -expectType(fs.mkdirSync("./index.d.ts")); - -// Testing ^promises.d.ts -expectType( - (await fsPromises.readFile("./index.d.ts", { encoding: "utf-8" })).toString(), -); -expectType>(fsPromises.access("./index.d.ts")); -expectType>(fsPromises.appendFile("./index.d.ts", "test")); -expectType>(fsPromises.mkdir("./index.d.ts")); - -Bun.env; - -Bun.version; - -setImmediate; -clearImmediate; -setInterval; -clearInterval; -setTimeout; -clearTimeout; - -const arg = new AbortSignal(); -arg; - -const e = new CustomEvent("asdf"); -console.log(e); - -exports; -module.exports; - -global.AbortController; -global.Bun; - -const er = new DOMException(); -er.name; -er.HIERARCHY_REQUEST_ERR; - -new Request(new Request("https://example.com"), {}); -new Request("", { method: "POST" }); - -Bun.sleepSync(1); // sleep for 1 ms (not recommended) -await Bun.sleep(1); // sleep for 1 ms (recommended) - -Blob; -WebSocket; diff --git a/packages/bun-types/tests/hashing.test-d.ts b/packages/bun-types/tests/hashing.test-d.ts deleted file mode 100644 index 16d65737d0..0000000000 --- a/packages/bun-types/tests/hashing.test-d.ts +++ /dev/null @@ -1 +0,0 @@ -const hash: bigint = Bun.hash.wyhash("asdf", 1234n); diff --git a/packages/bun-types/tests/headers.test-d.ts b/packages/bun-types/tests/headers.test-d.ts deleted file mode 100644 index 711384ddca..0000000000 --- a/packages/bun-types/tests/headers.test-d.ts +++ /dev/null @@ -1,6 +0,0 @@ -const headers = new Headers(); -headers.append("Set-Cookie", "a=1"); -headers.append("Set-Cookie", "b=1; Secure"); - -console.log(headers.getAll("Set-Cookie")); // ["a=1", "b=1; Secure"] -console.log(headers.toJSON()); // { "set-cookie": "a=1, b=1; Secure" } diff --git a/packages/bun-types/tests/index.test-d.ts b/packages/bun-types/tests/index.test-d.ts deleted file mode 100644 index a8895fd75e..0000000000 --- a/packages/bun-types/tests/index.test-d.ts +++ /dev/null @@ -1 +0,0 @@ -const c1 = Bun.spawn(["echo", '"hi"']); diff --git a/packages/bun-types/tests/perf_hooks.test-d.ts b/packages/bun-types/tests/perf_hooks.test-d.ts deleted file mode 100644 index 6f6106048b..0000000000 --- a/packages/bun-types/tests/perf_hooks.test-d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { performance } from "node:perf_hooks"; - -performance.now(); -performance.timeOrigin; diff --git a/packages/bun-types/tests/toml.test-d.ts b/packages/bun-types/tests/toml.test-d.ts deleted file mode 100644 index ef71b3e489..0000000000 --- a/packages/bun-types/tests/toml.test-d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { expectType } from "tsd"; -import data from "../../../bunfig.toml"; - -expectType(data); diff --git a/packages/bun-types/timers.d.ts b/packages/bun-types/timers.d.ts deleted file mode 100644 index 0d2f3e745e..0000000000 --- a/packages/bun-types/timers.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 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/v18.0.0/lib/timers.js) - */ - -declare module "timers" { - class Timer { - ref(): Timer; - unref(): Timer; - hasRef(): boolean; - } - - const _exported: { - clearTimeout: (timer: Timer | number) => void; - clearInterval: (timer: Timer | number) => void; - setInterval: ( - cb: CallableFunction, - msDelay: number, - ...args: any[] - ) => Timer; - setTimeout: ( - cb: CallableFunction, - msDelay: number, - ...args: any[] - ) => Timer; - setImmediate: (cb: CallableFunction, ...args: any[]) => Timer; - }; - export = _exported; -} -declare module "node:timers" { - import timers = require("timers"); - export = timers; -} diff --git a/packages/bun-types/tls.d.ts b/packages/bun-types/tls.d.ts deleted file mode 100644 index 386b4e9d69..0000000000 --- a/packages/bun-types/tls.d.ts +++ /dev/null @@ -1,1280 +0,0 @@ -/** - * 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/v18.0.0/lib/tls.js) - */ -declare module "tls" { - // import { X509Certificate } from "node:crypto"; - import * as net from "node:net"; - import * as stream from "stream"; - import { BunFile } from "bun"; - const CLIENT_RENEG_LIMIT: number; - const CLIENT_RENEG_WINDOW: number; - interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } - interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: Dict; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - fingerprint256: string; - ext_key_usage: string[]; - serialNumber: string; - raw: Buffer; - } - interface DetailedPeerCertificate extends PeerCertificate { - issuerCertificate: DetailedPeerCertificate; - } - interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - /** - * IETF name for the cipher suite. - */ - standardName: string; - } - interface EphemeralKeyInfo { - /** - * The supported types are 'DH' and 'ECDH'. - */ - type: string; - /** - * The name property is available only when type is 'ECDH'. - */ - name?: string | undefined; - /** - * The size of parameter of an ephemeral key exchange. - */ - size: number; - } - interface KeyObject { - /** - * Private keys in PEM format. - */ - pem: string | Buffer; - /** - * Optional passphrase. - */ - passphrase?: string | undefined; - } - interface PxfObject { - /** - * PFX or PKCS12 encoded private key and certificate chain. - */ - buf: string | Buffer; - /** - * Optional passphrase. - */ - passphrase?: string | undefined; - } - interface TLSSocketOptions - extends SecureContextOptions, - CommonConnectionOptions { - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean | undefined; - /** - * An optional net.Server instance. - */ - // server?: net.Server | undefined; - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer | undefined; - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - 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); - /** - * This property is `true` if the peer certificate was signed by one of the CAs - * specified when creating the `tls.TLSSocket` instance, otherwise `false`. - * @since v0.11.4 - */ - authorized: boolean; - /** - * 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; - /** - * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. - * @since v0.11.4 - */ - 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. - * - * 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. - * @since v11.2.0 - */ - // getCertificate(): PeerCertificate | object | null; - /** - * 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 - * 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'`. - * - * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. - * @since v5.0.0 - */ - // getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; - /** - * 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](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. 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; - /** - * 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](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. - * - * 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; - /** - * 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; - /** - * 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[]; - /** - * 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; - /** - * See `Session Resumption` for more information. - * @since v0.5.6 - * @return `true` if the session was reused, `false` otherwise. - */ - // isSessionReused(): boolean; - /** - * 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`. - * - * 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; - /** - * 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`. - * @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. - * - * 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. - * @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; - 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; - 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; - 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; - 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; - 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; - } - 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. - * @default false - */ - enableTrace?: boolean | undefined; - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean | undefined; - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) - */ - ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * 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; - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. - * @default true - */ - rejectUnauthorized?: boolean | undefined; - } - interface TlsOptions - extends SecureContextOptions, - CommonConnectionOptions, - net.ServerOpts { - /** - * Abort the connection if the SSL/TLS handshake does not finish in the - * specified number of milliseconds. A 'tlsClientError' is emitted on - * the tls.Server object whenever a handshake times out. Default: - * 120000 (120 seconds). - */ - handshakeTimeout?: number | undefined; - /** - * The number of seconds after which a TLS session created by the - * server will no longer be resumable. See Session Resumption for more - * information. Default: 300. - */ - sessionTimeout?: number | undefined; - /** - * 48-bytes of cryptographically strong pseudo-random data. - */ - ticketKeys?: Buffer | undefined; - /** - * - * @param socket - * @param identity identity parameter sent from the client. - * @return pre-shared key that must either be - * a buffer or `null` to stop the negotiation process. Returned PSK must be - * compatible with the selected cipher's digest. - * - * When negotiating TLS-PSK (pre-shared keys), this function is called - * with the identity provided by the client. - * If the return value is `null` the negotiation process will stop and an - * "unknown_psk_identity" alert message will be sent to the other party. - * If the server wishes to hide the fact that the PSK identity was not known, - * the callback must provide some random data as `psk` to make the connection - * fail with "decrypt_error" before negotiation is finished. - * PSK ciphers are disabled by default, and using TLS-PSK thus - * 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 | TypedArray | null; - /** - * hint to send to a client to help - * with selecting the identity during TLS-PSK negotiation. Will be ignored - * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be - * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. - */ - pskIdentityHint?: string | undefined; - } - interface PSKCallbackNegotation { - psk: DataView | 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 - // checkServerIdentity?: typeof checkServerIdentity | undefined; - servername?: string | undefined; // SNI TLS Extension - session?: Buffer | undefined; - minDHSize?: number | undefined; - lookup?: net.LookupFunction | undefined; - timeout?: number | undefined; - /** - * When negotiating TLS-PSK (pre-shared keys), this function is called - * with optional identity `hint` provided by the server or `null` - * in case of TLS 1.3 where `hint` was removed. - * It will be necessary to provide a custom `tls.checkServerIdentity()` - * for the connection as the default one will try to check hostname/IP - * of the server against the certificate but that's not applicable for PSK - * because there won't be a certificate present. - * More information can be found in the RFC 4279. - * - * @param hint message sent from the server to help client - * decide which identity to use during negotiation. - * Always `null` if TLS 1.3 is used. - * @returns Return `null` to stop the negotiation process. `psk` must be - * compatible with the selected cipher's digest. - * `identity` must use UTF-8 encoding. - */ - 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). - * - * 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, 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. - * @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(options: SecureContextOptions): void; - /** - * 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 - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - * 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: () => 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: () => 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: () => 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: () => 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: () => 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: () => 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 - * the well-known CAs curated by Mozilla. Mozilla's CAs are completely - * replaced when CAs are explicitly specified using this option. - */ - ca?: - | string - | Buffer - | TypedArray - | BunFile - | Array - | undefined; - /** - * Cert chains in PEM format. One cert chain should be provided per - * private key. Each cert chain should consist of the PEM formatted - * certificate for a provided private key, followed by the PEM - * formatted intermediate certificates (if any), in order, and not - * including the root CA (the root CA must be pre-known to the peer, - * see ca). When providing multiple cert chains, they do not have to - * be in the same order as their private keys in key. If the - * intermediate certificates are not provided, the peer will not be - * able to validate the certificate, and the handshake will fail. - */ - cert?: - | string - | Buffer - | TypedArray - | BunFile - | Array - | undefined; - /** - * Colon-separated list of supported signature algorithms. The list - * can contain digest algorithms (SHA256, MD5 etc.), public key - * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g - * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). - */ - // sigalgs?: string | undefined; - /** - * Cipher suite specification, replacing the default. For more - * information, see modifying the default cipher suite. Permitted - * ciphers can be obtained via tls.getCiphers(). Cipher names must be - * uppercased in order for OpenSSL to accept them. - */ - ciphers?: string | undefined; - /** - * Name of an OpenSSL engine which can provide the client certificate. - */ - // clientCertEngine?: string | undefined; - /** - * PEM formatted CRLs (Certificate Revocation Lists). - */ - // crl?: string | Buffer | Array | undefined; - /** - * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use - * openssl dhparam to create the parameters. The key length must be - * greater than or equal to 1024 bits or else an error will be thrown. - * Although 1024 bits is permissible, use 2048 bits or larger for - * stronger security. If omitted or invalid, the parameters are - * silently discarded and DHE ciphers will not be available. - */ - // dhparam?: string | Buffer | undefined; - /** - * A string describing a named curve or a colon separated list of curve - * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key - * agreement. Set to auto to select the curve automatically. Use - * crypto.getCurves() to obtain a list of available curve names. On - * recent releases, openssl ecparam -list_curves will also display the - * name and description of each available elliptic curve. Default: - * tls.DEFAULT_ECDH_CURVE. - */ - // ecdhCurve?: string | undefined; - /** - * Attempt to use the server's cipher suite preferences instead of the - * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be - * set in secureOptions - */ - // honorCipherOrder?: boolean | undefined; - /** - * Private keys in PEM format. PEM allows the option of private keys - * being encrypted. Encrypted keys will be decrypted with - * options.passphrase. Multiple keys using different algorithms can be - * provided either as an array of unencrypted key strings or buffers, - * or an array of objects in the form {pem: [, - * passphrase: ]}. The object form can only occur in an array. - * object.passphrase is optional. Encrypted keys will be decrypted with - * object.passphrase if provided, or options.passphrase if it is not. - */ - key?: - | string - | Buffer - | BunFile - | TypedArray - | Array - | undefined; - /** - * Name of an OpenSSL engine to get private key from. Should be used - * together with privateKeyIdentifier. - */ - // privateKeyEngine?: string | undefined; - /** - * Identifier of a private key managed by an OpenSSL engine. Should be - * used together with privateKeyEngine. Should not be set together with - * key, because both options define a private key in different ways. - */ - // privateKeyIdentifier?: string | undefined; - /** - * Optionally set the maximum TLS version to allow. One - * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the - * `secureProtocol` option, use one or the other. - * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using - * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to - * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. - */ - // maxVersion?: SecureVersion | undefined; - /** - * Optionally set the minimum TLS version to allow. One - * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the - * `secureProtocol` option, use one or the other. It is not recommended to use - * less than TLSv1.2, but it may be required for interoperability. - * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using - * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to - * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. - */ - // minVersion?: SecureVersion | undefined; - /** - * Shared passphrase used for a single private key and/or a PFX. - */ - passphrase?: string | undefined; - /** - * PFX or PKCS12 encoded private key and certificate chain. pfx is an - * alternative to providing key and cert individually. PFX is usually - * encrypted, if it is, passphrase will be used to decrypt it. Multiple - * PFX can be provided either as an array of unencrypted PFX buffers, - * or an array of objects in the form {buf: [, - * passphrase: ]}. The object form can only occur in an array. - * object.passphrase is optional. Encrypted PFX will be decrypted with - * object.passphrase if provided, or options.passphrase if it is not. - */ - // pfx?: string | Buffer | Array | undefined; - /** - * Optionally affect the OpenSSL protocol behavior, which is not - * usually necessary. This should be used carefully if at all! Value is - * a numeric bitmask of the SSL_OP_* options from OpenSSL Options - */ - secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options - /** - * Legacy mechanism to select the TLS protocol version to use, it does - * not support independent control of the minimum and maximum version, - * and does not support limiting the protocol to TLSv1.3. Use - * minVersion and maxVersion instead. The possible values are listed as - * SSL_METHODS, use the function names as strings. For example, use - * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow - * any TLS protocol version up to TLSv1.3. It is not recommended to use - * TLS versions less than 1.2, but it may be required for - * interoperability. Default: none, see minVersion. - */ - // secureProtocol?: string | undefined; - /** - * Opaque identifier used by servers to ensure session state is not - * shared between applications. Unused by clients. - */ - // sessionIdContext?: string | undefined; - /** - * 48-bytes of cryptographically strong pseudo-random data. - * See Session Resumption for more information. - */ - // ticketKeys?: Buffer | undefined; - /** - * The number of seconds after which a TLS session created by the - * server will no longer be resumable. See Session Resumption for more - * information. Default: 300. - */ - // sessionTimeout?: number | undefined; - } - interface SecureContext { - context: any; - } - /** - * Verifies the certificate `cert` is issued to `hostname`. - * - * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on - * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). - * - * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as - * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. - * - * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The - * overwriting function can call `tls.checkServerIdentity()` of course, to augment - * the checks done with additional verification. - * - * This function is only called if the certificate passed all other checks, such as - * being issued by trusted CA (`options.ca`). - * - * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name - * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use - * a custom`options.checkServerIdentity` function that implements the desired behavior. - * @since v0.8.4 - * @param hostname The host name or IP address to verify the certificate against. - * @param cert A `certificate object` representing the peer's certificate. - */ - // function checkServerIdentity( - // 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 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; - /** - * 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 createSecureContext(options?: SecureContextOptions): SecureContext; - /** - * Returns an array with the names of the supported TLS ciphers. The names are - * lower-case for historical reasons, but must be uppercased to be used in - * the `ciphers` option of {@link createSecureContext}. - * - * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. - * - * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for - * TLSv1.2 and below. - * - * ```js - * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] - * ``` - * @since v0.10.2 - */ - function getCiphers(): string[]; - /** - * The default curve name to use for ECDH key agreement in a tls server. - * The default value is 'auto'. See tls.createSecureContext() for further - * information. - */ - let DEFAULT_ECDH_CURVE: string; - /** - * The default value of the maxVersion option of - * tls.createSecureContext(). It can be assigned any of the supported TLS - * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: - * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets - * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the highest maximum - * is used. - */ - let DEFAULT_MAX_VERSION: SecureVersion; - /** - * The default value of the minVersion option of tls.createSecureContext(). - * It can be assigned any of the supported TLS protocol versions, - * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless - * changed using CLI options. Using --tls-min-v1.0 sets the default to - * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using - * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options - * are provided, the lowest minimum is used. - */ - let DEFAULT_MIN_VERSION: SecureVersion; - let DEFAULT_CIPHERS: string; - /** - * An immutable array of strings representing the root certificates (in PEM - * format) used for verifying peer certificates. This is the default value - * of the ca option to tls.createSecureContext(). - */ - // const rootCertificates: ReadonlyArray; -} -declare module "node:tls" { - export * from "tls"; -} diff --git a/packages/bun-types/tsconfig.docs.json b/packages/bun-types/tsconfig.docs.json deleted file mode 100644 index 5b357801a5..0000000000 --- a/packages/bun-types/tsconfig.docs.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "composite": true, - "noEmit": true, - "lib": ["ESNext"], - "baseUrl": ".", - "rootDir": ".", - "outFile": "./types.d.ts", - "skipLibCheck": true, - "target": "esnext", - "disableSolutionSearching": true - }, - "include": ["./*.d.ts", "dist"], - "exclude": [ - "node_modules", - "./node_modules", - "./node_modules/*", - "./node_modules/@types/node/index.d.ts" - ] -} diff --git a/packages/bun-types/tsconfig.json b/packages/bun-types/tsconfig.json index ed37def147..42a706acb0 100644 --- a/packages/bun-types/tsconfig.json +++ b/packages/bun-types/tsconfig.json @@ -9,15 +9,8 @@ "allowSyntheticDefaultImports": true, "disableSolutionSearching": true, "noUnusedLocals": true, - "outDir": "build", "noEmit": true, "resolveJsonModule": true }, - "exclude": [ - "dist", - "node_modules", - "./node_modules", - "./node_modules/*", - "./node_modules/@types/node/index.d.ts" - ] + "exclude": ["dist", "node_modules"] } diff --git a/packages/bun-types/tty.d.ts b/packages/bun-types/tty.d.ts deleted file mode 100644 index 89e8d88b75..0000000000 --- a/packages/bun-types/tty.d.ts +++ /dev/null @@ -1,209 +0,0 @@ -/** - * 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/v18.0.0/lib/tty.js) - */ -declare module "tty" { - 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; - } - /** - * -1 - to the left from cursor - * 0 - the entire line - * 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; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "resize"): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "resize", listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "resize", listener: () => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "resize", listener: () => void): this; - prependOnceListener( - event: string, - listener: (...args: any[]) => void, - ): this; - prependOnceListener(event: "resize", listener: () => void): this; - /** - * `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; - /** - * `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; - /** - * `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; - /** - * `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; - /** - * 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 - */ - getWindowSize(): [number, number]; - /** - * A `number` specifying the number of columns the TTY currently has. This property - * is updated whenever the `'resize'` event is emitted. - * @since v0.7.7 - */ - columns: number; - /** - * A `number` specifying the number of rows the TTY currently has. This property - * is updated whenever the `'resize'` event is emitted. - * @since v0.7.7 - */ - rows: number; - /** - * A `boolean` that is always `true`. - * @since v0.5.8 - */ - isTTY: boolean; - } -} -declare module "node:tty" { - export * from "tty"; -} diff --git a/packages/bun-types/typedoc.json b/packages/bun-types/typedoc.json deleted file mode 100644 index 0fc79d1113..0000000000 --- a/packages/bun-types/typedoc.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "media": "images", - "tsconfig": "./tsconfig.docs.json", - "entryPoints": ["./dist/types.d.ts"], - "out": "docs", - "exclude": ["**/node_modules/**"], - "disableSources": true -} diff --git a/packages/bun-types/url.d.ts b/packages/bun-types/url.d.ts deleted file mode 100644 index c63a911743..0000000000 --- a/packages/bun-types/url.d.ts +++ /dev/null @@ -1,347 +0,0 @@ -/** - * 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/v18.0.0/lib/url.js) - */ -declare module "url" { - import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; - // Input to `url.format` - interface UrlObject { - auth?: string | null | undefined; - hash?: string | null | undefined; - host?: string | null | undefined; - hostname?: string | null | undefined; - href?: string | null | undefined; - pathname?: string | null | undefined; - protocol?: string | null | undefined; - search?: string | null | undefined; - slashes?: boolean | null | undefined; - port?: string | number | null | undefined; - query?: string | null | ParsedUrlQueryInput | undefined; - } - // Output of `url.parse` - interface Url { - auth: string | null; - hash: string | null; - host: string | null; - hostname: string | null; - href: string; - path: string | null; - pathname: string | null; - protocol: string | null; - search: string | null; - slashes: boolean | null; - port: string | null; - query: string | null | ParsedUrlQuery; - } - interface UrlWithParsedQuery extends Url { - query: ParsedUrlQuery; - } - interface UrlWithStringQuery extends Url { - query: string | null; - } - /** - * 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.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: 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; - /** - * The `url.resolve()` method resolves a target URL relative to a base URL in a - * manner similar to that of a web browser resolving an anchor tag. - * - * ```js - * const url = require('url'); - * url.resolve('/one/two/three', 'four'); // '/one/two/four' - * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' - * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' - * ``` - * - * To achieve the same result using the WHATWG URL API: - * - * ```js - * function resolve(from, to) { - * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); - * if (resolvedUrl.protocol === 'resolve:') { - * // `from` is a relative URL. - * const { pathname, search, hash } = resolvedUrl; - * return pathname + search + hash; - * } - * return resolvedUrl.toString(); - * } - * - * resolve('/one/two/three', 'four'); // '/one/two/four' - * resolve('http://example.com/', '/one'); // 'http://example.com/one' - * resolve('http://example.com/one', '/two'); // 'http://example.com/two' - * ``` - * @since v0.1.25 - * @deprecated Legacy: Use the WHATWG URL API instead. - * @param from The base URL to use if `to` is a relative URL. - * @param to The target URL to resolve. - */ - function resolve(from: string, to: string): string; - /** - * 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 - * control characters are correctly encoded when converting into 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(path: string): URL; - interface URLFormatOptions { - auth?: boolean | undefined; - fragment?: boolean | undefined; - search?: boolean | undefined; - unicode?: boolean | undefined; - } - - /** - * The URL interface represents an object providing static methods used for - * creating object URLs. - */ - interface URL { - hash: string; - host: string; - hostname: string; - href: string; - toString(): string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toJSON(): string; - } - - interface URLSearchParams { - /** Appends a specified key/value pair as a new search parameter. */ - append(name: string, value: string): void; - /** Deletes the given search parameter, and its associated value, from the list of all search parameters. */ - delete(name: string): void; - /** Returns the first value associated to the given search parameter. */ - get(name: string): string | null; - /** Returns all the values association with a given search parameter. */ - getAll(name: string): string[]; - /** Returns a Boolean indicating if such a search parameter exists. */ - has(name: string): boolean; - /** Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. */ - set(name: string, value: string): void; - sort(): void; - /** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ - toString(): string; - forEach( - callbackfn: (value: string, key: string, parent: URLSearchParams) => void, - thisArg?: any, - ): void; - } -} - -declare module "node:url" { - export * from "url"; -} diff --git a/packages/bun-types/util.d.ts b/packages/bun-types/util.d.ts deleted file mode 100644 index 7ac9d2b386..0000000000 --- a/packages/bun-types/util.d.ts +++ /dev/null @@ -1,1955 +0,0 @@ -/** - * 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/v18.0.0/lib/util.js) - */ -declare module "util" { - import * as types from "node:util/types"; - - export { 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; - } - /** - * 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. - * @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. - * ``` - */ - 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 - * }); - * ``` - */ - // FIXME: util.getSystemErrorName is typed, but is not defined in the polyfill - // 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 - * }); - * ``` - */ - // FIXME: util.getSystemErrorMap is typed, but is not defined in the polyfill - // 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.'); - * ``` - * @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. - */ - // FIXME: util.toUSVString is typed, but is not defined in the polyfill - // 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 }) - * ); - * ``` - * - * The `numericSeparator` option adds an underscore every three digits to all - * numbers. - * - * ```js - * const { inspect } = require('util'); - * - * const thousand = 1_000; - * const million = 1_000_000; - * const bigNumber = 123_456_789n; - * const bigDecimal = 1_234.123_45; - * - * console.log(thousand, million, bigNumber, bigDecimal); - * // 1_000 1_000_000 123_456_789n 1_234.123_45 - * ``` - * - * `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. - * @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: Dict<[number, number]>; - let styles: { - [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; - } - /** - * 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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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'); - * ``` - * @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; - } - /** - * 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; - * }); - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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 - * ``` - * @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`. - * @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. - */ - 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" - * ``` - */ - // FIXME: util.stripVTControlCharacters is typed, but is not defined in the polyfill - // 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 && Object.hasOwn(err, 'reason') && err.reason === null; // true - * }); - * ``` - * @param original An `async` function - * @return a callback style function - */ - export function callbackify( - fn: () => Promise, - ): (callback: (err: ErrnoException) => void) => void; - export function callbackify( - fn: () => Promise, - ): (callback: (err: ErrnoException, result: TResult) => void) => void; - export function callbackify( - fn: (arg1: T1) => Promise, - ): (arg1: T1, callback: (err: ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1) => Promise, - ): ( - arg1: T1, - callback: (err: ErrnoException, result: TResult) => void, - ) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2) => Promise, - ): (arg1: T1, arg2: T2, callback: (err: ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2) => Promise, - ): ( - arg1: T1, - arg2: T2, - callback: (err: 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: ErrnoException) => void, - ) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, - ): ( - arg1: T1, - arg2: T2, - arg3: T3, - callback: (err: 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: 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: 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: 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: ErrnoException | null, result: TResult) => void, - ) => void; - 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: ErrnoException) => void, - ) => void; - 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: ErrnoException | null, result: TResult) => void, - ) => void; - export interface CustomPromisifyLegacy - extends Function { - __promisify__: TCustom; - } - export interface CustomPromisifySymbol - extends Function { - [promisify.custom]: TCustom; - } - 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' - * ``` - */ - 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; - 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; - 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; - export function promisify(fn: Function): Function; - export namespace promisify { - /** - * That can be used to declare custom promisified variants of functions. - */ - const custom: unique symbol; - } - - //// parseArgs - /** - * Provides a higher level API for command-line argument parsing than interacting - * with `process.argv` directly. Takes a specification for the expected arguments - * and returns a structured object with the parsed options and positionals. - * - * ```js - * import { parseArgs } from 'node:util'; - * const args = ['-f', '--bar', 'b']; - * const options = { - * foo: { - * type: 'boolean', - * short: 'f', - * }, - * bar: { - * type: 'string', - * }, - * }; - * const { - * values, - * positionals, - * } = parseArgs({ args, options }); - * console.log(values, positionals); - * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] - * ``` - * @since v18.3.0, v16.17.0 - * @param config Used to provide arguments for parsing and to configure the parser. - * @return The parsed command line arguments: - */ - export function parseArgs( - config?: T, - ): ParsedResults; - interface ParseArgsOptionConfig { - /** - * Type of argument. - */ - type: "string" | "boolean"; - /** - * Whether this option can be provided multiple times. - * If `true`, all values will be collected in an array. - * If `false`, values for the option are last-wins. - * @default false. - */ - multiple?: boolean | undefined; - /** - * A single character alias for the option. - */ - short?: string | undefined; - /** - * The default option value when it is not set by args. - * It must be of the same type as the the `type` property. - * When `multiple` is `true`, it must be an array. - * @since v18.11.0 - */ - default?: string | boolean | string[] | boolean[] | undefined; - } - interface ParseArgsOptionsConfig { - [longOption: string]: ParseArgsOptionConfig; - } - export interface ParseArgsConfig { - /** - * Array of argument strings. - */ - args?: string[] | undefined; - /** - * Used to describe arguments known to the parser. - */ - options?: ParseArgsOptionsConfig | undefined; - /** - * Should an error be thrown when unknown arguments are encountered, - * or when arguments are passed that do not match the `type` configured in `options`. - * @default true - */ - strict?: boolean | undefined; - /** - * Whether this command accepts positional arguments. - */ - allowPositionals?: boolean | undefined; - /** - * Return the parsed tokens. This is useful for extending the built-in behavior, - * from adding additional checks through to reprocessing the tokens in different ways. - * @default false - */ - tokens?: boolean | undefined; - } - /* - IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. - TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 - This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". - But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. - So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. - This is technically incorrect but is a much nicer UX for the common case. - The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. - */ - type IfDefaultsTrue = T extends true - ? IfTrue - : T extends false - ? IfFalse - : IfTrue; - - // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` - type IfDefaultsFalse = T extends false - ? IfFalse - : T extends true - ? IfTrue - : IfFalse; - - type ExtractOptionValue< - T extends ParseArgsConfig, - O extends ParseArgsOptionConfig, - > = IfDefaultsTrue< - T["strict"], - O["type"] extends "string" - ? string - : O["type"] extends "boolean" - ? boolean - : string | boolean, - string | boolean - >; - - type ParsedValues = IfDefaultsTrue< - T["strict"], - unknown, - { [longOption: string]: undefined | string | boolean } - > & - (T["options"] extends ParseArgsOptionsConfig - ? { - -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< - T["options"][LongOption]["multiple"], - undefined | Array>, - undefined | ExtractOptionValue - >; - } - : {}); - - type ParsedPositionals = IfDefaultsTrue< - T["strict"], - IfDefaultsFalse, - IfDefaultsTrue - >; - - type PreciseTokenForOptions< - K extends string, - O extends ParseArgsOptionConfig, - > = O["type"] extends "string" - ? { - kind: "option"; - index: number; - name: K; - rawName: string; - value: string; - inlineValue: boolean; - } - : O["type"] extends "boolean" - ? { - kind: "option"; - index: number; - name: K; - rawName: string; - value: undefined; - inlineValue: undefined; - } - : OptionToken & { name: K }; - - type TokenForOptions< - T extends ParseArgsConfig, - K extends keyof T["options"] = keyof T["options"], - > = K extends unknown - ? T["options"] extends ParseArgsOptionsConfig - ? PreciseTokenForOptions - : OptionToken - : never; - - type ParsedOptionToken = IfDefaultsTrue< - T["strict"], - TokenForOptions, - OptionToken - >; - - type ParsedPositionalToken = IfDefaultsTrue< - T["strict"], - IfDefaultsFalse< - T["allowPositionals"], - { kind: "positional"; index: number; value: string }, - never - >, - IfDefaultsTrue< - T["allowPositionals"], - { kind: "positional"; index: number; value: string }, - never - > - >; - - type ParsedTokens = Array< - | ParsedOptionToken - | ParsedPositionalToken - | { kind: "option-terminator"; index: number } - >; - - type PreciseParsedResults = IfDefaultsFalse< - T["tokens"], - { - values: ParsedValues; - positionals: ParsedPositionals; - tokens: ParsedTokens; - }, - { - values: ParsedValues; - positionals: ParsedPositionals; - } - >; - - type OptionToken = - | { - kind: "option"; - index: number; - name: string; - rawName: string; - value: string; - inlineValue: boolean; - } - | { - kind: "option"; - index: number; - name: string; - rawName: string; - value: undefined; - inlineValue: undefined; - }; - - type Token = - | OptionToken - | { kind: "positional"; index: number; value: string } - | { kind: "option-terminator"; index: number }; - - // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. - // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. - type ParsedResults = ParseArgsConfig extends T - ? { - values: { - [longOption: string]: - | undefined - | string - | boolean - | Array; - }; - positionals: string[]; - tokens?: Token[]; - } - : PreciseParsedResults; - - export interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; - } -} -declare module "node:util" { - export * from "util"; -} -declare module "sys" { - export * from "util"; -} -declare module "node:sys" { - export * from "util"; -} - -declare module "util/types" { - export * from "util/types"; -} -declare module "util/types" { - import { KeyObject } from "node:crypto"; - import { ArrayBufferView } from "bun"; - - /** - * 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 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 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 CryptoKey; -} -declare module "node:util" { - export * from "util"; -} -declare module "node:util/types" { - export * from "util/types"; -} diff --git a/packages/bun-types/vm.d.ts b/packages/bun-types/vm.d.ts deleted file mode 100644 index 649abc037b..0000000000 --- a/packages/bun-types/vm.d.ts +++ /dev/null @@ -1,509 +0,0 @@ -/** - * The `node:vm` module enables compiling and running code within V8 Virtual - * Machine contexts. - * - * **The `node:vm` module is not a security** - * **mechanism. Do not use it to run untrusted code.** - * - * JavaScript code can be compiled and run immediately or - * compiled, saved, and run later. - * - * A common use case is to run the code in a different V8 Context. This means - * invoked code has a different global object than the invoking code. - * - * One can provide the context by `contextifying` an - * object. The invoked code treats any property in the context like a - * global variable. Any changes to global variables caused by the invoked - * code are reflected in the context object. - * - * ```js - * const vm = require('node:vm'); - * - * const x = 1; - * - * const context = { x: 2 }; - * vm.createContext(context); // Contextify the object. - * - * const code = 'x += 40; var y = 17;'; - * // `x` and `y` are global variables in the context. - * // Initially, x has the value 2 because that is the value of context.x. - * vm.runInContext(code, context); - * - * console.log(context.x); // 42 - * console.log(context.y); // 17 - * - * console.log(x); // 1; y is not defined. - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.1.0/lib/vm.js) - */ -declare module "vm" { - interface Context extends Record {} - interface BaseOptions { - /** - * Specifies the filename used in stack traces produced by this script. - * Default: `''`. - */ - filename?: string | undefined; - /** - * Specifies the line number offset that is displayed in stack traces produced by this script. - * Default: `0`. - */ - lineOffset?: number | undefined; - /** - * Specifies the column number offset that is displayed in stack traces produced by this script. - * @default 0 - */ - columnOffset?: number | undefined; - } - interface ScriptOptions extends BaseOptions { - /** - * V8's code cache data for the supplied source. - */ - cachedData?: Buffer | ArrayBufferView | undefined; - /** @deprecated in favor of `script.createCachedData()` */ - produceCachedData?: boolean | undefined; - } - interface RunningScriptOptions extends BaseOptions { - /** - * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. - * Default: `true`. - */ - displayErrors?: boolean | undefined; - /** - * Specifies the number of milliseconds to execute code before terminating execution. - * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. - * Not implemented yet - */ - timeout?: number | undefined; - /** - * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. - * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. - * If execution is terminated, an `Error` will be thrown. - * Default: `false`. - * Not implemented yet - */ - breakOnSigint?: boolean | undefined; - } - interface RunningScriptInNewContextOptions extends RunningScriptOptions { - /** - * Human-readable name of the newly created context. - * Not implemented yet - */ - contextName?: CreateContextOptions["name"]; - /** - * Not implemented yet */ - contextOrigin?: CreateContextOptions["origin"]; - contextCodeGeneration?: CreateContextOptions["codeGeneration"]; - /** - * Not implemented yet - */ - microtaskMode?: CreateContextOptions["microtaskMode"]; - } - interface RunningCodeOptions extends RunningScriptOptions { - cachedData?: ScriptOptions["cachedData"]; - } - interface RunningCodeInNewContextOptions - extends RunningScriptInNewContextOptions { - cachedData?: ScriptOptions["cachedData"]; - } - interface CompileFunctionOptions extends BaseOptions { - /** - * Provides an optional data with V8's code cache data for the supplied source. - */ - cachedData?: Buffer | undefined; - /** - * Specifies whether to produce new cache data. - * Default: `false`, - */ - produceCachedData?: boolean | undefined; - /** - * 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. - * @default 'VM Context i' Where i is an ascending numerical index of the created context. - */ - name?: string | undefined; - /** - * Corresponds to the newly created context for display purposes. - * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), - * like the value of the `url.origin` property of a URL object. - * Most notably, this string should omit the trailing slash, as that denotes a path. - * @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; - /** - * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. - */ - microtaskMode?: "afterEvaluate" | undefined; - } - - /** - * 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 | string); - /** - * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access - * to local scope. - * - * The following example compiles code that increments a global variable, sets - * the value of another global variable, then execute the code multiple times. - * The globals are contained in the `context` object. - * - * ```js - * const vm = require('node:vm'); - * - * const context = { - * animal: 'cat', - * count: 2, - * }; - * - * const script = new vm.Script('count += 1; name = "kitty";'); - * - * vm.createContext(context); - * for (let i = 0; i < 10; ++i) { - * script.runInContext(context); - * } - * - * console.log(context); - * // Prints: { animal: 'cat', count: 12, name: 'kitty' } - * ``` - * - * Using the `timeout` or `breakOnSigint` options will result in new event loops - * and corresponding threads being started, which have a non-zero performance - * overhead. - * @since v0.3.1 - * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. - * @return the result of the very last statement executed in the script. - */ - runInContext( - contextifiedObject: Context, - options?: RunningScriptOptions, - ): any; - /** - * First contextifies the given `contextObject`, runs the compiled code contained - * by the `vm.Script` object within the created context, and returns the result. - * Running code does not have access to local scope. - * - * The following example compiles code that sets a global variable, then executes - * the code multiple times in different contexts. The globals are set on and - * contained within each individual `context`. - * - * ```js - * const vm = require('node:vm'); - * - * const script = new vm.Script('globalVar = "set"'); - * - * const contexts = [{}, {}, {}]; - * contexts.forEach((context) => { - * script.runInNewContext(context); - * }); - * - * console.log(contexts); - * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] - * ``` - * @since v0.3.1 - * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. - * @return the result of the very last statement executed in the script. - */ - runInNewContext( - contextObject?: Context, - options?: RunningScriptInNewContextOptions, - ): any; - /** - * Runs the compiled code contained by the `vm.Script` within the context of the - * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. - * - * The following example compiles code that increments a `global` variable then - * executes that code multiple times: - * - * ```js - * const vm = require('node:vm'); - * - * global.globalVar = 0; - * - * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); - * - * for (let i = 0; i < 1000; ++i) { - * script.runInThisContext(); - * } - * - * console.log(globalVar); - * - * // 1000 - * ``` - * @since v0.3.1 - * @return the result of the very last statement executed in the script. - */ - runInThisContext(options?: RunningScriptOptions): any; - /** - * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any - * time and any number of times. - * - * The code cache of the `Script` doesn't contain any JavaScript observable - * states. The code cache is safe to be saved along side the script source and - * used to construct new `Script` instances multiple times. - * - * Functions in the `Script` source can be marked as lazily compiled and they are - * not compiled at construction of the `Script`. These functions are going to be - * compiled when they are invoked the first time. The code cache serializes the - * metadata that V8 currently knows about the `Script` that it can use to speed up - * future compilations. - * - * ```js - * const script = new vm.Script(` - * function add(a, b) { - * return a + b; - * } - * - * const x = add(1, 2); - * `); - * - * const cacheWithoutAdd = script.createCachedData(); - * // In `cacheWithoutAdd` the function `add()` is marked for full compilation - * // upon invocation. - * - * script.runInThisContext(); - * - * const cacheWithAdd = script.createCachedData(); - * // `cacheWithAdd` contains fully compiled function `add()`. - * ``` - * @since v10.6.0 - */ - createCachedData(): Buffer; - /** @deprecated in favor of `script.createCachedData()` */ - cachedDataProduced?: boolean | undefined; - /** - * When `cachedData` is supplied to create the `vm.Script`, this value will be set - * to either `true` or `false` depending on acceptance of the data by V8\. - * Otherwise the value is `undefined`. - * @since v5.7.0 - */ - cachedDataRejected?: boolean | undefined; - cachedData?: Buffer | undefined; - /** - * When the script is compiled from a source that contains a source map magic - * comment, this property will be set to the URL of the source map. - * - * ```js - * import vm from 'node:vm'; - * - * const script = new vm.Script(` - * function myFunc() {} - * //# sourceMappingURL=sourcemap.json - * `); - * - * console.log(script.sourceMapURL); - * // Prints: sourcemap.json - * ``` - * @since v19.1.0, v18.13.0 - */ - sourceMapURL?: string | undefined; - } - /** - * If given a `contextObject`, the `vm.createContext()` method will `prepare - * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, - * the `contextObject` will be the global object, retaining all of its existing - * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables - * will remain unchanged. - * - * ```js - * const vm = require('node:vm'); - * - * global.globalVar = 3; - * - * const context = { globalVar: 1 }; - * vm.createContext(context); - * - * vm.runInContext('globalVar *= 2;', context); - * - * console.log(context); - * // Prints: { globalVar: 2 } - * - * console.log(global.globalVar); - * // Prints: 3 - * ``` - * - * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, - * empty `contextified` object will be returned. - * - * The `vm.createContext()` method is primarily useful for creating a single - * context that can be used to run multiple scripts. For instance, if emulating a - * web browser, the method can be used to create a single context representing a - * window's global object, then run all `