Better types (#7670)

* Rewrite bun-types to include @types/node

* Incorporate new commits

* Update bun.lockb

* [autofix.ci] apply automated fixes

* Update readme, add back webkit

* Updates

* BunJS -> Bun

* Switch init to @types/bun

* [autofix.ci] apply automated fixes

* Tweaks

* Revert docs changes

* Fix bugs

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
Colin McDonnell
2023-12-18 13:27:48 -08:00
committed by GitHub
parent a1a4178c3f
commit 31c17a1bb3
107 changed files with 3045 additions and 33520 deletions

View File

@@ -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",
},
};

View File

@@ -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).

View File

@@ -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<Func extends (...args: any[]) => 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<T>(
actual: unknown,
expected: T,
message?: string | Error,
): asserts actual is T;
/**
* Tests strict inequality between the `actual` and `expected` parameters as
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
*
* ```js
* import assert from '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<T>(
actual: unknown,
expected: T,
message?: string | Error,
): asserts actual is T;
/**
* Tests for deep strict inequality. Opposite of {@link deepStrictEqual}.
*
* ```js
* import assert from '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<unknown>) | Promise<unknown>,
message?: string | Error,
): Promise<void>;
function rejects(
block: (() => Promise<unknown>) | Promise<unknown>,
error: AssertPredicate,
message?: string | Error,
): Promise<void>;
/**
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
* calls the function and awaits the returned promise to complete. It will then
* check that the promise is not rejected.
*
* If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If
* the function does not return a promise, `assert.doesNotReject()` will return a
* rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases
* the error handler is skipped.
*
* Using `assert.doesNotReject()` is actually not useful because there is little
* benefit in catching a rejection and then rejecting it again. Instead, consider
* adding a comment next to the specific code path that should not reject and keep
* error messages as expressive as possible.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation
* function. See {@link throws} for more details.
*
* Besides the async nature to await the completion behaves identically to {@link doesNotThrow}.
*
* ```js
* import assert from '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<unknown>) | Promise<unknown>,
message?: string | Error,
): Promise<void>;
function doesNotReject(
block: (() => Promise<unknown>) | Promise<unknown>,
error: AssertPredicate,
message?: string | Error,
): Promise<void>;
/**
* Expects the `string` input to match the regular expression.
*
* ```js
* import assert from '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;
}

View File

@@ -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<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
fn: Func,
type?: string,
thisArg?: ThisArg,
): Func;
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
* @since v0.7.0
* @param fn The function to bind to the current `AsyncResource`.
*/
bind<Func extends (...args: any[]) => any>(fn: Func): Func;
/**
* Call the provided function with the provided arguments in the execution context
* of the async resource. This will establish the context, trigger the AsyncHooks
* before callbacks, call the function, trigger the AsyncHooks after callbacks, and
* then restore the original execution context.
* @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<This, Result>(
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<T> {
/**
* 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<Func extends (...args: any[]) => any>(fn: Func): Func;
/**
* Captures the current execution context and returns a function that accepts a
* function as an argument. Whenever the returned function is called, it
* calls the function passed to it within the captured context.
*
* ```js
* const asyncLocalStorage = new AsyncLocalStorage();
* const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
* const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
* console.log(result); // returns 123
* ```
*
* AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
* async context tracking purposes, for example:
*
* ```js
* class Foo {
* #runInAsyncScope = AsyncLocalStorage.snapshot();
*
* get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
* }
*
* const foo = asyncLocalStorage.run(123, () => new Foo());
* console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
* ```
* @since v0.7.0
* @experimental
* @return A new function with the signature `(fn: (...args) : R, ...args) : R`.
*/
static snapshot(): <R, TArgs extends any[]>(
fn: (...args: TArgs) => R,
...args: TArgs
) => R;
/**
* Disables the instance of `AsyncLocalStorage`. All subsequent calls
* to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
*
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
* instance will be exited.
*
* Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores
* 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<R, TArgs extends any[]>(
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<R, TArgs extends any[]>(
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";
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -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;
}

View File

@@ -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;
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<T> = import("async_hooks").AsyncLocalStorage<T>;
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<T>(
store: AsyncLocalStorage<T>,
transform?: TransformCallback<T>,
): void;
unbindStore(store: AsyncLocalStorage<unknown>): void;
runStores(
context: unknown,
fn: (...args: unknown[]) => unknown,
receiver?: unknown,
...args: unknown[]
): any;
}
type TransformCallback<T> = (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<T>(
fn: (...values: any[]) => T,
context?: any,
thisArg?: any,
...args: any[]
): any;
tracePromise<T>(
fn: (...values: any[]) => Promise<T>,
context?: any,
thisArg?: any,
...args: any[]
): Promise<any>;
traceCallback<T>(
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";
}

View File

@@ -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<LookupAddress[]>;
// function __promisify__(
// hostname: string,
// options?: LookupOneOptions | number,
// ): Promise<LookupAddress>;
// function __promisify__(
// hostname: string,
// options: LookupOptions,
// ): Promise<LookupAddress | LookupAddress[]>;
// }
/**
* 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`:
*
* <omitted>
*
* On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`.
* @since v0.1.27
* @param hostname Host name to resolve.
* @param [rrtype='A'] Resource record type.
*/
export function resolve(
hostname: string,
callback: (err: 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<string[]>;
function __promisify__(
hostname: string,
rrtype: "ANY",
): Promise<AnyRecord[]>;
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function __promisify__(
hostname: string,
rrtype: "NAPTR",
): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function __promisify__(
hostname: string,
rrtype: "SRV",
): Promise<SrvRecord[]>;
function __promisify__(
hostname: string,
rrtype: "TXT",
): Promise<string[][]>;
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<string[]>;
// function __promisify__(
// hostname: string,
// options: ResolveWithTtlOptions,
// ): Promise<RecordWithTtl[]>;
// function __promisify__(
// hostname: string,
// options?: ResolveOptions,
// ): Promise<string[] | RecordWithTtl[]>;
// }
/**
* 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<string[]>;
// function __promisify__(
// hostname: string,
// options: ResolveWithTtlOptions,
// ): Promise<RecordWithTtl[]>;
// function __promisify__(
// hostname: string,
// options?: ResolveOptions,
// ): Promise<string[] | RecordWithTtl[]>;
// }
/**
* 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<string[]>;
}
/**
* 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<CaaRecord[]>;
}
/**
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
* @since v0.1.27
*/
export function resolveMx(
hostname: string,
callback: (err: ErrnoException | null, addresses: MxRecord[]) => void,
): void;
export namespace resolveMx {
function __promisify__(hostname: string): Promise<MxRecord[]>;
}
/**
* 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<NaptrRecord[]>;
}
/**
* 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<string[]>;
}
/**
* 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<string[]>;
}
/**
* 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<SoaRecord>;
}
/**
* 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<SrvRecord[]>;
}
/**
* 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<string[][]>;
}
/**
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
* The `ret` argument passed to the `callback` function will be an array containing
* various types of records. Each object has a property `type` that indicates the
* type of the current record. And depending on the `type`, additional properties
* will be present on the object:
*
* <omitted>
*
* Here is an example of the `ret` object passed to the callback:
*
* ```js
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
* { type: 'CNAME', value: 'example.com' },
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
* { type: 'NS', value: 'ns1.example.com' },
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
* { type: 'SOA',
* nsname: 'ns1.example.com',
* hostmaster: 'admin.example.com',
* serial: 156696742,
* refresh: 900,
* retry: 900,
* expire: 1800,
* minttl: 60 } ]
* ```
*
* DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC
* 8482](https://tools.ietf.org/html/rfc8482).
*/
// export function resolveAny(
// hostname: string,
// callback: (err: ErrnoException | null, addresses: AnyRecord[]) => void,
// ): void;
// export namespace resolveAny {
// function __promisify__(hostname: string): Promise<AnyRecord[]>;
// }
/**
* 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<string>): void;
/**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
* that are currently configured for DNS resolution. A string will include a port
* section if a custom port is used.
*
* ```js
* [
* '4.4.4.4',
* '2001:4860:4860::8888',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]
* ```
* @since v0.11.3
*/
export function getServers(): string[];
/**
* Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: sets default `verbatim` `false`.
* * `verbatim`: sets default `verbatim` `true`.
*
* The default is `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";
}

View File

@@ -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<LookupAddress>;
function lookup(
hostname: string,
options: LookupOneOptions,
): Promise<LookupAddress>;
function lookup(
hostname: string,
options: LookupAllOptions,
): Promise<LookupAddress[]>;
function lookup(
hostname: string,
options: LookupOptions,
): Promise<LookupAddress | LookupAddress[]>;
function lookup(hostname: string): Promise<LookupAddress>;
/**
* 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`:
*
* <omitted>
*
* 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<string[]>;
function resolve(hostname: string, rrtype: "A"): Promise<string[]>;
function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>;
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>;
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function resolve(hostname: string, rrtype: "NS"): Promise<string[]>;
function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
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<string[]>;
function resolve4(
hostname: string,
options: ResolveWithTtlOptions,
): Promise<RecordWithTtl[]>;
function resolve4(
hostname: string,
options: ResolveOptions,
): Promise<string[] | RecordWithTtl[]>;
/**
* 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<string[]>;
function resolve6(
hostname: string,
options: ResolveWithTtlOptions,
): Promise<RecordWithTtl[]>;
function resolve6(
hostname: string,
options: ResolveOptions,
): Promise<string[] | RecordWithTtl[]>;
/**
* 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:
*
* <omitted>
*
* 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<AnyRecord[]>;
/**
* 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<CaaRecord[]>;
/**
* 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<string[]>;
/**
* 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<MxRecord[]>;
/**
* 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<NaptrRecord[]>;
/**
* 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<string[]>;
/**
* 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<string[]>;
/**
* 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<SoaRecord>;
/**
* 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<SrvRecord[]>;
/**
* 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<string[][]>;
/**
* 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<string[]>;
/**
* 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<string>): 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";
}

View File

@@ -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<EventEmitter | number>;
/**
* 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<T>(fn: (...args: any[]) => T, ...args: any[]): T;
/**
* Explicitly adds an emitter to the domain. If any event handlers called by
* the emitter throw an error, or if the emitter emits an `'error'` event, it
* will be routed to the domain's `'error'` event, just like with implicit
* binding.
*
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
* the domain `'error'` handler.
*
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
* from that one, and bound to this one instead.
* @param emitter emitter or timer to be added to the domain
*/
add(emitter: EventEmitter | 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<T extends Function>(callback: T): T;
/**
* This method is almost identical to {@link bind}. However, in
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
*
* In this way, the common `if (err) return callback(err);` pattern can be replaced
* with a single error handler in a single place.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.intercept((data) => {
* // Note, the first argument is never passed to the
* // callback since it is assumed to be the 'Error' argument
* // and thus intercepted by the domain.
*
* // If this throws, it will also be passed to the domain
* // so the error-handling logic can be moved to the 'error'
* // event on the domain instead of being repeated throughout
* // the program.
* return cb(null, JSON.parse(data));
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The intercepted function
*/
intercept<T extends Function>(callback: T): T;
}
function create(): Domain;
}
declare module "node:domain" {
export * from "domain";
}

View File

@@ -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<string | symbol, any[]> = Record<
string | symbol,
any[]
>,
> {
/**
* Alias for `emitter.on(eventName, listener)`.
*/
addListener<K extends keyof Events>(
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<K extends keyof Events>(
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<K extends keyof Events>(
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<K extends keyof Events>(
eventName: K,
listener: (...args: Events[K]) => void,
): this;
/**
* Alias for `emitter.removeListener()`.
*/
off<K extends keyof Events>(
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<K extends keyof Events>(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<K extends keyof Events>(
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<K extends keyof Events>(
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<string | symbol>;
}
/**
* 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<any[]>;
static once(
emitter: DOMEventTarget,
eventName: string,
options?: StaticEventEmitterOptions,
): Promise<any[]>;
/**
* ```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<any>;
/**
* 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<DOMEventTarget | EventEmitter>
): 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;
}

View File

@@ -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<Record<string, Narrow<FFIFunction>>>,
> {
interface Library<Fns extends Readonly<Record<string, Narrow<FFIFunction>>>> {
symbols: ConvertFns<Fns>;
/**
@@ -568,6 +558,7 @@ declare module "bun:ffi" {
? FFITypeStringToType[T]
: never;
// eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
type _Narrow<T, U> = [U] extends [T] ? U : Extract<T, U>;
type Narrow<T = unknown> =
| _Narrow<T, 0 | (number & {})>
@@ -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<A[L]>] }
: [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<NonNullable<Fns[K]["returns"]>>];
};
@@ -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<Fns extends Record<string, Narrow<FFIFunction>>>(
function dlopen<Fns extends Record<string, Narrow<FFIFunction>>>(
name: string,
symbols: Fns,
): Library<Fns>;
@@ -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<Fns extends Record<string, Narrow<FFIFunction>>>(
function linkSymbols<Fns extends Record<string, Narrow<FFIFunction>>>(
symbols: Fns,
): Library<Fns>;
@@ -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;
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<T extends ArrayBufferView> {
bytesRead: number;
buffer: T;
}
interface FileReadOptions<T extends ArrayBufferView = Buffer> {
/**
* @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<void>;
/**
* 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<void>;
/**
* 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<number>;
/**
* Renames `oldPath` to `newPath`.
* @since v0.0.67
* @return Fulfills with `undefined` upon success.
*/
function rename(oldPath: PathLike, newPath: PathLike): Promise<void>;
/**
* 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<void>;
/**
* 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<string | undefined>;
/**
* 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<void>;
/**
* Asynchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
function mkdir(
path: PathLike,
options?: Mode | MakeDirectoryOptions | null | undefined,
): Promise<string | undefined>;
/**
* 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<string[]>;
/**
* 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<Buffer[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used.
*/
function readdir(
path: PathLike,
options?:
| (ObjectEncodingOptions & {
withFileTypes?: false | undefined;
recursive?: boolean | undefined;
})
| BufferEncoding
| null,
): Promise<string[] | Buffer[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options 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<Dirent[]>;
/**
* 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<string>;
/**
* 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<Buffer>;
/**
* 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<string | Buffer>;
/**
* 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<void>;
/**
* 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<Stats>;
function lstat(
path: PathLike,
options: StatOptions & {
bigint: true;
},
): Promise<BigIntStats>;
function lstat(
path: PathLike,
options?: StatOptions,
): Promise<Stats | BigIntStats>;
/**
* @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<Stats>;
function stat(
path: PathLike,
options: StatOptions & {
bigint: true;
},
): Promise<BigIntStats>;
function stat(
path: PathLike,
options?: StatOptions,
): Promise<Stats | BigIntStats>;
/**
* 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<void>;
/**
* 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<void>;
/**
* Changes the permissions of a file.
* @since v0.0.67
* @return Fulfills with `undefined` upon success.
*/
function chmod(path: PathLike, mode: Mode): Promise<void>;
/**
* 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<void>;
/**
* Changes the ownership on a symbolic link.
* @return Fulfills with `undefined` upon success.
*/
function lchown(path: PathLike, uid: number, gid: number): Promise<void>;
/**
* Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a
* symbolic link, then the link is not dereferenced: instead, the timestamps of
* the symbolic link itself are changed.
* @since v0.0.67
* @return Fulfills with `undefined` upon success.
*/
function lutimes(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
): Promise<void>;
/**
* 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<void>;
/**
* 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<void>;
/**
* 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<string>;
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used.
*/
function realpath(
path: PathLike,
options: BufferEncodingOption,
): Promise<Buffer>;
/**
* 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<string | Buffer>;
/**
* 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<string>;
/**
* 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<Buffer>;
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `"utf8"` is used.
*/
function mkdtemp(
prefix: string,
options?: EncodingOption | null,
): Promise<string | Buffer>;
/**
* 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<void>;
/**
* 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<void>;
/**
* 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<Buffer>;
/**
* 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<string>;
/**
* 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<string | Buffer>;
/**
* 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<void>;
/**
* 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<boolean>;
/**
* @deprecated Use `fs.promises.rm()` instead.
*
* Asynchronously remove a directory.
*
* ```ts
* import { rmdir } from 'fs/promises';
*
* // remove a directory
* await rmdir('/tmp/mydir'); // Promise<void>
* ```
*
* To remove a directory recursively, use `fs.promises.rm()` instead, with the `recursive` option set to `true`.
*/
function rmdir(path: PathLike, options?: RmDirOptions): Promise<void>;
interface FileChangeInfo<T extends string | Buffer> {
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<FileChangeInfo<Buffer>>;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
function watch(
filename: PathLike,
options?: WatchOptions | BufferEncoding,
): AsyncIterable<FileChangeInfo<string>>;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
function watch(
filename: PathLike,
options: WatchOptions | string,
):
| AsyncIterable<FileChangeInfo<string>>
| AsyncIterable<FileChangeInfo<Buffer>>;
/**
* Asynchronously copies the entire directory structure from `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<void>;
}
declare module "node:fs/promises" {
export * from "fs/promises";
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,9 @@
// Project: https://github.com/oven-sh/bun
// Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference types="node" />
/// <reference types="ws" />
// This file is bundled so that your TypeScript editor integration loads it faster.

File diff suppressed because it is too large Load Diff

View File

@@ -1,50 +1,18 @@
/* eslint-disable */
// Type definitions for bun 0.0
// Project: https://github.com/oven-sh/bun
// Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference path="./assert.d.ts" />
/// <reference path="./async_hooks.d.ts" />
/// <reference path="./buffer.d.ts" />
/// <reference path="./bun-test.d.ts" />
/// <reference path="./bun.d.ts" />
/// <reference path="./child_process.d.ts" />
/// <reference path="./console.d.ts" />
/// <reference path="./constants.d.ts" />
/// <reference path="./crypto.d.ts" />
/// <reference path="./diagnostics_channel.d.ts" />
/// <reference path="./dns.d.ts" />
/// <reference path="./dns/promises.d.ts" />
/// <reference path="./domain.d.ts" />
/// <reference path="./events.d.ts" />
/// <reference path="./ffi.d.ts" />
/// <reference path="./fs.d.ts" />
/// <reference path="./fs/promises.d.ts" />
/// <reference types="node" />
/// <reference types="ws" />
// contributors: uncomment this to detect conflicts with lib.dom.d.ts
//// <reference lib="dom" />
/// <reference path="./globals.d.ts" />
/// <reference path="./bun.d.ts" />
/// <reference path="./ffi.d.ts" />
/// <reference path="./test.d.ts" />
/// <reference path="./html-rewriter.d.ts" />
/// <reference path="./http.d.ts" />
/// <reference path="./jsc.d.ts" />
/// <reference path="./module.d.ts" />
/// <reference path="./net.d.ts" />
/// <reference path="./os.d.ts" />
/// <reference path="./path.d.ts" />
/// <reference path="./perf_hooks.d.ts" />
/// <reference path="./punycode.d.ts" />
/// <reference path="./querystring.d.ts" />
/// <reference path="./readline.d.ts" />
/// <reference path="./readline/promises.d.ts" />
/// <reference path="./sqlite.d.ts" />
/// <reference path="./stream.d.ts" />
/// <reference path="./string_decoder.d.ts" />
/// <reference path="./supports-color.d.ts" />
/// <reference path="./timers.d.ts" />
/// <reference path="./tls.d.ts" />
/// <reference path="./tty.d.ts" />
/// <reference path="./url.d.ts" />
/// <reference path="./util.d.ts" />
/// <reference path="./vm.d.ts" />
/// <reference path="./worker_threads.d.ts" />
/// <reference path="./ws.d.ts" />
/// <reference path="./zlib.d.ts" />

View File

@@ -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<string, number>;
protectedObjectTypeCounts: Record<string, number>;
};
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 <numSamples 'functionName#hash:JITType:bytecodeIndex'>
* 273 'visit#<nil>:DFG:bc#63'
* 121 'walk#<nil>: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;
}

View File

@@ -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[];
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<T> {
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<NetworkInterfaceInfo[]>;
/**
* Returns the string path of the current user's home directory.
*
* On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it
* uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory.
*
* On Windows, it uses the `USERPROFILE` environment variable if defined.
* Otherwise it uses the path to the profile directory of the current user.
*/
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<Buffer>;
function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>;
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";
}

77
packages/bun-types/overrides.d.ts vendored Normal file
View File

@@ -0,0 +1,77 @@
declare namespace NodeJS {
type _BunEnv = import("bun").Env;
interface ProcessVersions extends Dict<string> {
bun: string;
}
interface ProcessEnv extends Dict<string>, _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<boolean>;
}
declare module "tls" {
// eslint-disable-next-line no-duplicate-imports
import { BunFile } from "bun";
type BunConnectionOptions = Omit<ConnectionOptions, "ca" | "tls" | "cert"> & {
/**
* 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<string | Buffer | BunFile>
| 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<string | Buffer | NodeJS.TypedArray | BunFile>
| 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: <string|buffer>[,
* passphrase: <string>]}. 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<string | Buffer | BunFile | NodeJS.TypedArray | KeyObject>
| undefined;
};
function connect(
options: BunConnectionOptions,
secureConnectListener?: () => void,
): TLSSocket;
}

View File

@@ -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"
}

View File

@@ -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";
}

View File

@@ -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<T extends (...params: any[]) => 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<EntryType>;
// 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<number, number>;
// /**
// * 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";
}

View File

@@ -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<number>): 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";
}

View File

@@ -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<string | string[]> {}
interface ParsedUrlQueryInput
extends Dict<
| string
| number
| boolean
| ReadonlyArray<string>
| ReadonlyArray<number>
| ReadonlyArray<boolean>
| null
> {}
/**
* The `querystring.stringify()` method produces a URL query string from a
* given `obj` by iterating through the object's "own properties".
*
* It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) |
* [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to
* empty strings.
*
* ```js
* querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
* // Returns 'foo=bar&#x26;baz=qux&#x26;baz=quux&#x26;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&#x26;abc=xyz&#x26;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&#x26;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";
}

View File

@@ -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<string>;
}
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";
}

View File

@@ -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<string>;
question(query: string, options: Abortable): Promise<string>;
}
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<void>;
/**
* 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";
}

View File

@@ -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";

View File

@@ -1,5 +1,6 @@
/// <reference path="../index.d.ts" />
import { join } from "path";
// @ts-ignore
import pkg from "../dist/package.json";
const __dirname = new URL(".", import.meta.url).pathname;

View File

@@ -169,7 +169,7 @@ declare module "bun:sqlite" {
sqlQuery: string,
...bindings: ParamsType[]
): void;
/**
/**
This is an alias of {@link Database.prototype.run}
*/
exec<ParamsType extends SQLQueryBindings[]>(
@@ -200,14 +200,11 @@ declare module "bun:sqlite" {
* @returns `Statment` instance
*
* Under the hood, this calls `sqlite3_prepare_v3`.
*
*/
query<ReturnType, ParamsType extends SQLQueryBindings | SQLQueryBindings[]>(
sqlQuery: string,
): Statement<
ReturnType,
ParamsType extends Array<any> ? ParamsType : [ParamsType]
>;
): // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
Statement<ReturnType, ParamsType extends any[] ? ParamsType : [ParamsType]>;
/**
* 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<any> ? ParamsType : [ParamsType]
>;
): // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
Statement<ReturnType, ParamsType extends any[] ? ParamsType : [ParamsType]>;
/**
* 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;

File diff suppressed because it is too large Load Diff

View File

@@ -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";
}

View File

@@ -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;
}

View File

@@ -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<T extends Readonly<[any, ...any[]]>>(
table: ReadonlyArray<T>,
table: readonly T[],
): (
label: string,
fn: (...args: [...T]) => void | Promise<unknown>,
options?: number | TestOptions,
) => void;
each<T extends Array<any>>(
table: ReadonlyArray<T>,
each<T extends any[]>(
table: readonly T[],
): (
label: string,
fn: (...args: Readonly<T>) => void | Promise<unknown>,
options?: number | TestOptions,
) => void;
each<T>(
table: Array<T>,
table: T[],
): (
label: string,
fn: (...args: T[]) => void | Promise<unknown>,
options?: number | TestOptions,
) => void;
};
}
/**
* Describes a group of related tests.
*
@@ -320,7 +320,7 @@ declare module "bun:test" {
| (() => void | Promise<unknown>)
| ((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<T extends Readonly<[any, ...any[]]>>(
table: ReadonlyArray<T>,
table: readonly T[],
): (
label: string,
fn: (...args: [...T]) => void | Promise<unknown>,
options?: number | TestOptions,
) => void;
each<T extends Array<any>>(
table: ReadonlyArray<T>,
each<T extends any[]>(
table: readonly T[],
): (
label: string,
fn: (...args: Readonly<T>) => void | Promise<unknown>,
options?: number | TestOptions,
) => void;
each<T>(
table: Array<T>,
table: T[],
): (
label: string,
fn: (...args: T[]) => void | Promise<unknown>,
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<string | number>,
value?: unknown,
): void;
/**
@@ -1406,15 +1406,15 @@ declare module "bun:test" {
/**
* Ensure that a mock function is called with specific arguments.
*/
toHaveBeenCalledWith(...expected: Array<unknown>): void;
toHaveBeenCalledWith(...expected: unknown[]): void;
/**
* Ensure that a mock function is called with specific arguments for the last call.
*/
toHaveBeenLastCalledWith(...expected: Array<unknown>): void;
toHaveBeenLastCalledWith(...expected: unknown[]): void;
/**
* Ensure that a mock function is called with specific arguments for the nth call.
*/
toHaveBeenNthCalledWith(n: number, ...expected: Array<unknown>): void;
toHaveBeenNthCalledWith(n: number, ...expected: unknown[]): void;
}
/**
@@ -1456,7 +1456,7 @@ declare module "bun:test" {
this: TesterContext,
a: any,
b: any,
customTesters: Array<Tester>,
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<T> = keyof {
[K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K];
@@ -1637,7 +1637,7 @@ declare namespace JestMock {
| MockFunctionResultReturn<T>
| 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<T extends FunctionLike = UnknownFunction> = {
interface MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> {
type: "return";
/**
* Result of a single call to a mock function that returned.
*/
value: ReturnType<T>;
};
}
type MockFunctionResultThrow = {
interface MockFunctionResultThrow {
type: "throw";
/**
* Result of a single call to a mock function that threw.
*/
value: unknown;
};
}
type MockFunctionState<T extends FunctionLike = FunctionLike> = {
interface MockFunctionState<T extends FunctionLike = FunctionLike> {
/**
* 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<number>;
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<MockFunctionResult<T>>;
};
}
export interface MockInstance<T extends FunctionLike = UnknownFunction> {
_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<T[K_2]>;
>(object: T, propertyKey: K_2, value: V): Replaced<T[K_2]>;
export type ResolveType<T extends FunctionLike> =
ReturnType<T> extends PromiseLike<infer U> ? U : never;
@@ -1937,11 +1933,11 @@ declare namespace JestMock {
): V_1 extends ClassLike | FunctionLike ? Spied<V_1> : never;
};
export type UnknownClass = {
new (...args: Array<unknown>): unknown;
};
export interface UnknownClass {
new (...args: unknown[]): unknown;
}
export type UnknownFunction = (...args: Array<unknown>) => unknown;
export type UnknownFunction = (...args: unknown[]) => unknown;
export {};
}

View File

@@ -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 {};

View File

@@ -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);

View File

@@ -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<void>(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;

View File

@@ -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;
};

View File

@@ -0,0 +1,3 @@
import { webcrypto } from "crypto";
webcrypto.CryptoKey;

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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<string>(arg);
// });
// // @ts-expect-error
// e1.on("qwer", (_) => {});
const e2 = new EventEmitter();
e2.on("qwer", (_: any) => {
_;
});
e2.on("asdf", arg => {
expectType<any>(arg);
});

View File

@@ -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<CString>(lib.symbols.sqlite3_libversion());
tsd.expectType<number>(lib.symbols.add(1, 2));
tsd.expectType<Pointer | null>(lib.symbols.ptr_type(0));
tsd.expectType<Pointer | null>(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<libParams[0], number>(true);
tsd.expectTypeEquals<libParams[1], number>(true);
tsd.expectTypeEquals<libParams[2], number>(true);
tsd.expectTypeEquals<libParams[3], number>(true);
tsd.expectTypeEquals<libParams[4], number>(true);
tsd.expectTypeEquals<libParams[5], number>(true);
tsd.expectTypeEquals<libParams[6], number>(true);
tsd.expectTypeEquals<libParams[7], number>(true);
tsd.expectTypeEquals<libParams[8], number>(true);
tsd.expectTypeEquals<libParams[9], number>(true);
tsd.expectTypeEquals<libParams[10], number>(true);
tsd.expectTypeEquals<libParams[11], number>(true);
tsd.expectTypeEquals<libParams[12], number>(true);
tsd.expectTypeEquals<libParams[13], number>(true);
tsd.expectTypeEquals<libParams[14], number>(true);
tsd.expectTypeEquals<libParams[15], number>(true);
tsd.expectTypeEquals<libParams[16], number>(true);
tsd.expectTypeEquals<libParams[17], number>(true);
tsd.expectTypeEquals<libParams[18], number>(true);
tsd.expectTypeEquals<libParams[19], number>(true);
tsd.expectTypeEquals<libParams[20], number>(true);
tsd.expectTypeEquals<libParams[21], number>(true);
tsd.expectTypeEquals<libParams[22], boolean>(true);
tsd.expectTypeEquals<libParams[23], Pointer>(true);
tsd.expectTypeEquals<libParams[24], Pointer>(true);
tsd.expectTypeEquals<libParams[25], undefined>(true);
tsd.expectTypeEquals<libParams[26], CString>(true);
tsd.expectTypeEquals<libParams[27], number | bigint>(true);
tsd.expectTypeEquals<libParams[28], number | bigint>(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<CString>(lib2.symbols.sqlite3_libversion());
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
tsd.expectType<void>(lib2.symbols.multi_args(1, 2));
tsd.expectTypeEquals<
ReturnType<(typeof lib2)["symbols"]["no_returns"]>,
undefined
>(true);
tsd.expectTypeEquals<Parameters<(typeof lib2)["symbols"]["no_args"]>, []>(true);
tsd.expectType<number>(read.u8(0));
tsd.expectType<number>(read.u8(0, 0));
tsd.expectType<number>(read.i8(0, 0));
tsd.expectType<number>(read.u16(0, 0));
tsd.expectType<number>(read.i16(0, 0));
tsd.expectType<number>(read.u32(0, 0));
tsd.expectType<number>(read.i32(0, 0));
tsd.expectType<bigint>(read.u64(0, 0));
tsd.expectType<bigint>(read.i64(0, 0));
tsd.expectType<number>(read.f32(0, 0));
tsd.expectType<number>(read.f64(0, 0));
tsd.expectType<number>(read.ptr(0, 0));
tsd.expectType<number>(read.intptr(0, 0));

View File

@@ -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<Promise<boolean>>(exists("/etc/passwd"));
tsd.expectType<Promise<boolean>>(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) => {});

View File

@@ -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",
});

View File

@@ -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<ReadableStream<Uint8Array>>(Bun.file("index.test-d.ts").stream());
expectType<Promise<ArrayBuffer>>(Bun.file("index.test-d.ts").arrayBuffer());
expectType<Promise<string>>(Bun.file("index.test-d.ts").text());
expectType<number>(Bun.file("index.test-d.ts").size);
expectType<string>(Bun.file("index.test-d.ts").type);
// Hash
expectType<string>(new Bun.MD4().update("test").digest("hex"));
expectType<string>(new Bun.MD5().update("test").digest("hex"));
expectType<string>(new Bun.SHA1().update("test").digest("hex"));
expectType<string>(new Bun.SHA224().update("test").digest("hex"));
expectType<string>(new Bun.SHA256().update("test").digest("hex"));
expectType<string>(new Bun.SHA384().update("test").digest("hex"));
expectType<string>(new Bun.SHA512().update("test").digest("hex"));
expectType<string>(new Bun.SHA512_256().update("test").digest("hex"));
// Zlib Functions
expectType<Uint8Array>(Bun.deflateSync(new Uint8Array(128)));
expectType<Uint8Array>(Bun.gzipSync(new Uint8Array(128)));
expectType<Uint8Array>(
Bun.deflateSync(new Uint8Array(128), {
level: -1,
memLevel: 8,
strategy: 0,
windowBits: 15,
}),
);
expectType<Uint8Array>(
Bun.gzipSync(new Uint8Array(128), { level: 9, memLevel: 6, windowBits: 27 }),
);
expectType<Uint8Array>(Bun.inflateSync(new Uint8Array(64))); // Pretend this is DEFLATE compressed data
expectType<Uint8Array>(Bun.gunzipSync(new Uint8Array(64))); // Pretend this is GZIP compressed data
expectAssignable<ZlibCompressionOptions>({ windowBits: -11 });
// Other
expectType<Promise<number>>(Bun.write("test.json", "lol"));
expectType<Promise<number>>(Bun.write("test.json", new ArrayBuffer(32)));
expectType<URL>(Bun.pathToFileURL("/foo/bar.txt"));
expectType<string>(Bun.fileURLToPath(new URL("file:///foo/bar.txt")));
// Testing ../fs.d.ts
expectType<string>(
fs.readFileSync("./index.d.ts", { encoding: "utf-8" }).toString(),
);
expectType<boolean>(fs.existsSync("./index.d.ts"));
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
expectType<void>(fs.accessSync("./index.d.ts"));
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
expectType<void>(fs.appendFileSync("./index.d.ts", "test"));
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
expectType<void>(fs.mkdirSync("./index.d.ts"));
// Testing ^promises.d.ts
expectType<string>(
(await fsPromises.readFile("./index.d.ts", { encoding: "utf-8" })).toString(),
);
expectType<Promise<void>>(fsPromises.access("./index.d.ts"));
expectType<Promise<void>>(fsPromises.appendFile("./index.d.ts", "test"));
expectType<Promise<void>>(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);

View File

@@ -0,0 +1 @@
Bun.hash.wyhash("asdf", 1234n);

View File

@@ -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" }

View File

@@ -0,0 +1,2 @@
Bun.spawn(["echo", '"hi"']);
performance;

View File

@@ -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)) {

View File

@@ -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;

View File

@@ -0,0 +1,7 @@
import { performance as _performance } from "node:perf_hooks";
performance.now();
performance.timeOrigin;
_performance.now();
_performance.timeOrigin;

View File

@@ -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");

View File

@@ -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);
});

View File

@@ -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<User>({
}>({
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/chat") {
@@ -50,8 +49,9 @@ Bun.serve<User>({
"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<User>({
},
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<User>({
},
});
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(`<pre>${error}\n${error.stack}</pre>`, {
return new Response(`<pre>${error.message}\n${error.stack}</pre>`, {
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

View File

@@ -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<T>(_promise: Promise<T>): 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"
}

View File

@@ -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<Array<{ name: string; dob: number }>>(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<void>(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<Array<{ name: string; dob: number }>>(allResults3);

View File

@@ -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();
},

View File

@@ -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;

View File

@@ -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<any[][]>(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();

View File

@@ -0,0 +1,4 @@
import data from "./bunfig.toml";
import { expectType } from "./utilities.test";
expectType<any>(data);

View File

@@ -0,0 +1,10 @@
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectType: <T>(expression: T) => void;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectAssignable: <T>(expression: T) => void;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectNotAssignable: <T>(expression: any) => void;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectTypeEquals: <T, S>(
expression: T extends S ? (S extends T ? true : false) : false,
) => void;

View File

@@ -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
};

View File

@@ -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<MessageEvent>(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 };

View File

@@ -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 {};

View File

@@ -1,18 +0,0 @@
import { EventEmitter } from "events";
import { expectType } from "tsd";
const e1 = new EventEmitter<{
a: [string];
}>();
e1.on("a", arg => {
expectType<string>(arg);
});
// @ts-expect-error
e1.on("qwer", _ => {});
const e2 = new EventEmitter();
e2.on("qwer", _ => {});
e2.on("asdf", arg => {
expectType<any>(arg);
});

View File

@@ -1,5 +0,0 @@
/// <reference path="../index.d.ts" />
export * as fs from "fs";
export * as fsPromises from "fs/promises";
export default Bun;

View File

@@ -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<CString>(lib.symbols.sqlite3_libversion());
tsd.expectType<number>(lib.symbols.add(1, 2));
tsd.expectType<Pointer | null>(lib.symbols.ptr_type(0));
tc.assert<
tc.IsExact<
(typeof lib)["symbols"]["ptr_type"],
TypedArray | Pointer | CString
>
>;
tsd.expectType<Pointer | null>(lib.symbols.fn_type(0));
tc.assert<tc.IsExact<(typeof lib)["symbols"]["fn_type"], Pointer | JSCallback>>;
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<CString>(lib2.symbols.sqlite3_libversion());
tsd.expectType<void>(lib2.symbols.multi_args(1, 2));
tc.assert<tc.IsExact<ReturnType<(typeof lib2)["symbols"]["no_returns"]>, void>>;
tc.assert<tc.IsExact<Parameters<(typeof lib2)["symbols"]["no_args"]>, []>>;
tsd.expectType<number>(read.u8(0));
tsd.expectType<number>(read.u8(0, 0));
tsd.expectType<number>(read.i8(0, 0));
tsd.expectType<number>(read.u16(0, 0));
tsd.expectType<number>(read.i16(0, 0));
tsd.expectType<number>(read.u32(0, 0));
tsd.expectType<number>(read.i32(0, 0));
tsd.expectType<bigint>(read.u64(0, 0));
tsd.expectType<bigint>(read.i64(0, 0));
tsd.expectType<number>(read.f32(0, 0));
tsd.expectType<number>(read.f64(0, 0));
tsd.expectType<number>(read.ptr(0, 0));
tsd.expectType<number>(read.intptr(0, 0));

View File

@@ -1,98 +0,0 @@
import { ZlibCompressionOptions } from "bun";
import { expectAssignable, expectType } from "tsd";
import Bun, { fs, fsPromises } from "./exports";
// FileBlob
expectType<ReadableStream<Uint8Array>>(Bun.file("index.test-d.ts").stream());
expectType<Promise<ArrayBuffer>>(Bun.file("index.test-d.ts").arrayBuffer());
expectType<Promise<string>>(Bun.file("index.test-d.ts").text());
expectType<number>(Bun.file("index.test-d.ts").size);
expectType<string>(Bun.file("index.test-d.ts").type);
// Hash
expectType<string>(new Bun.MD4().update("test").digest("hex"));
expectType<string>(new Bun.MD5().update("test").digest("hex"));
expectType<string>(new Bun.SHA1().update("test").digest("hex"));
expectType<string>(new Bun.SHA224().update("test").digest("hex"));
expectType<string>(new Bun.SHA256().update("test").digest("hex"));
expectType<string>(new Bun.SHA384().update("test").digest("hex"));
expectType<string>(new Bun.SHA512().update("test").digest("hex"));
expectType<string>(new Bun.SHA512_256().update("test").digest("hex"));
// Zlib Functions
expectType<Uint8Array>(Bun.deflateSync(new Uint8Array(128)));
expectType<Uint8Array>(Bun.gzipSync(new Uint8Array(128)));
expectType<Uint8Array>(
Bun.deflateSync(new Uint8Array(128), {
level: -1,
memLevel: 8,
strategy: 0,
windowBits: 15,
}),
);
expectType<Uint8Array>(
Bun.gzipSync(new Uint8Array(128), { level: 9, memLevel: 6, windowBits: 27 }),
);
expectType<Uint8Array>(Bun.inflateSync(new Uint8Array(64))); // Pretend this is DEFLATE compressed data
expectType<Uint8Array>(Bun.gunzipSync(new Uint8Array(64))); // Pretend this is GZIP compressed data
expectAssignable<ZlibCompressionOptions>({ windowBits: -11 });
// Other
expectType<Promise<number>>(Bun.write("test.json", "lol"));
expectType<Promise<number>>(Bun.write("test.json", new ArrayBuffer(32)));
expectType<URL>(Bun.pathToFileURL("/foo/bar.txt"));
expectType<string>(Bun.fileURLToPath(new URL("file:///foo/bar.txt")));
// Testing ../fs.d.ts
expectType<string>(
fs.readFileSync("./index.d.ts", { encoding: "utf-8" }).toString(),
);
expectType<boolean>(fs.existsSync("./index.d.ts"));
expectType<void>(fs.accessSync("./index.d.ts"));
expectType<void>(fs.appendFileSync("./index.d.ts", "test"));
expectType<void>(fs.mkdirSync("./index.d.ts"));
// Testing ^promises.d.ts
expectType<string>(
(await fsPromises.readFile("./index.d.ts", { encoding: "utf-8" })).toString(),
);
expectType<Promise<void>>(fsPromises.access("./index.d.ts"));
expectType<Promise<void>>(fsPromises.appendFile("./index.d.ts", "test"));
expectType<Promise<void>>(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;

View File

@@ -1 +0,0 @@
const hash: bigint = Bun.hash.wyhash("asdf", 1234n);

View File

@@ -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" }

View File

@@ -1 +0,0 @@
const c1 = Bun.spawn(["echo", '"hi"']);

View File

@@ -1,4 +0,0 @@
import { performance } from "node:perf_hooks";
performance.now();
performance.timeOrigin;

View File

@@ -1,4 +0,0 @@
import { expectType } from "tsd";
import data from "../../../bunfig.toml";
expectType<any>(data);

View File

@@ -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;
}

File diff suppressed because it is too large Load Diff

View File

@@ -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"
]
}

View File

@@ -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"]
}

View File

@@ -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";
}

View File

@@ -1,8 +0,0 @@
{
"media": "images",
"tsconfig": "./tsconfig.docs.json",
"entryPoints": ["./dist/types.d.ts"],
"out": "docs",
"exclude": ["**/node_modules/**"],
"disableSources": true
}

View File

@@ -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&#x26;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&#x26;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";
}

Some files were not shown because too many files have changed in this diff Show More