From 26004bfccaead3d6ec143c03a09dc036cea2c2ae Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Wed, 21 Aug 2024 12:10:28 +0200 Subject: [PATCH] chore: replace standard and snazzy with neostandard (#3485) * use neostandard, drop standard and snazzy * apply automated fixes * fix manually linting errors * adapt recommended changes * add neostandard badge * remove node_modules * remove no-lone-blocks * fix linting issues * disable jsx, use cache, remove jest env --- README.md | 2 +- eslint.config.js | 27 ++++ lib/dispatcher/client-h1.js | 2 - lib/web/fetch/data-url.js | 2 +- lib/web/fetch/util.js | 2 +- package.json | 18 +-- test/fetch/pull-dont-push.js | 2 +- test/imports/undici-import.ts | 11 +- test/jest/mock-agent.test.js | 2 +- test/node-fetch/headers.js | 1 - test/node-fetch/main.js | 2 + test/node-test/abort-controller.js | 6 +- test/node-test/balanced-pool.js | 2 +- test/node-test/client-errors.js | 16 +-- test/types/agent.test-d.ts | 6 +- test/types/balanced-pool.test-d.ts | 3 +- test/types/client.test-d.ts | 128 +++++++++--------- test/types/connector.test-d.ts | 23 ++-- test/types/diagnostics-channel.test-d.ts | 74 +++++------ test/types/dispatcher.events.test-d.ts | 19 ++- test/types/dispatcher.test-d.ts | 88 ++++++------- test/types/env-http-proxy-agent.test-d.ts | 6 +- test/types/errors.test-d.ts | 4 +- test/types/event-source-d.ts | 2 +- test/types/fetch.test-d.ts | 11 +- test/types/global-dispatcher.test-d.ts | 4 +- test/types/header.test-d.ts | 16 +-- test/types/index.test-d.ts | 10 +- test/types/interceptor.test-d.ts | 6 +- test/types/mock-agent.test-d.ts | 20 +-- test/types/mock-client.test-d.ts | 5 +- test/types/mock-errors.test-d.ts | 2 +- test/types/mock-interceptor.test-d.ts | 56 ++++---- test/types/mock-pool.test-d.ts | 5 +- test/types/util.test-d.ts | 16 +-- test/wpt/runner/util.mjs | 2 +- types/agent.d.ts | 14 +- types/api.d.ts | 36 +++--- types/balanced-pool.d.ts | 22 ++-- types/client.d.ts | 23 ++-- types/diagnostics-channel.d.ts | 20 +-- types/dispatcher.d.ts | 151 +++++++++++----------- types/env-http-proxy-agent.d.ts | 4 +- types/errors.d.ts | 97 +++++++------- types/fetch.d.ts | 12 +- types/formdata.d.ts | 12 +- types/global-dispatcher.d.ts | 8 +- types/global-origin.d.ts | 10 +- types/handlers.d.ts | 8 +- types/header.d.ts | 4 +- types/index.d.ts | 84 ++++++------ types/interceptors.d.ts | 16 +-- types/mock-agent.d.ts | 34 ++--- types/mock-client.d.ts | 8 +- types/mock-errors.d.ts | 6 +- types/mock-interceptor.d.ts | 38 +++--- types/mock-pool.d.ts | 8 +- types/patch.d.ts | 64 ++++----- types/pool-stats.d.ts | 16 +-- types/pool.d.ts | 24 ++-- types/proxy-agent.d.ts | 8 +- types/readable.d.ts | 20 +-- types/retry-agent.d.ts | 2 +- types/retry-handler.d.ts | 16 +-- types/util.d.ts | 6 +- types/utility.d.ts | 8 +- types/webidl.d.ts | 2 +- types/websocket.d.ts | 2 +- 68 files changed, 704 insertions(+), 680 deletions(-) create mode 100644 eslint.config.js diff --git a/README.md b/README.md index f5691ea515b..7d509997e3b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # undici -[![Node CI](https://github.com/nodejs/undici/actions/workflows/nodejs.yml/badge.svg)](https://github.com/nodejs/undici/actions/workflows/nodejs.yml) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) [![npm version](https://badge.fury.io/js/undici.svg)](https://badge.fury.io/js/undici) [![codecov](https://codecov.io/gh/nodejs/undici/branch/main/graph/badge.svg?token=yZL6LtXkOA)](https://codecov.io/gh/nodejs/undici) +[![Node CI](https://github.com/nodejs/undici/actions/workflows/nodejs.yml/badge.svg)](https://github.com/nodejs/undici/actions/workflows/nodejs.yml) [![neostandard javascript style](https://img.shields.io/badge/neo-standard-7fffff?style=flat\&labelColor=ff80ff)](https://github.com/neostandard/neostandard) [![npm version](https://badge.fury.io/js/undici.svg)](https://badge.fury.io/js/undici) [![codecov](https://codecov.io/gh/nodejs/undici/branch/main/graph/badge.svg?token=yZL6LtXkOA)](https://codecov.io/gh/nodejs/undici) An HTTP/1.1 client, written from scratch for Node.js. diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000000..eac0c6960b1 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,27 @@ +'use strict' + +const neo = require('neostandard') + +module.exports = [ + ...neo({ + ignores: [ + 'lib/llhttp', + 'test/fixtures/wpt', + 'undici-fetch.js' + ], + noJsx: true, + ts: true + }), + { + rules: { + '@stylistic/comma-dangle': ['error', { + arrays: 'never', + objects: 'never', + imports: 'never', + exports: 'never', + functions: 'never' + }], + '@typescript-eslint/no-redeclare': 'off' + } + } +] diff --git a/lib/dispatcher/client-h1.js b/lib/dispatcher/client-h1.js index 2f1c96724d3..367b3c8d97d 100644 --- a/lib/dispatcher/client-h1.js +++ b/lib/dispatcher/client-h1.js @@ -78,7 +78,6 @@ async function lazyllhttp () { return await WebAssembly.instantiate(mod, { env: { - /* eslint-disable camelcase */ wasm_on_url: (p, at, len) => { /* istanbul ignore next */ @@ -117,7 +116,6 @@ async function lazyllhttp () { return currentParser.onMessageComplete() || 0 } - /* eslint-enable camelcase */ } }) } diff --git a/lib/web/fetch/data-url.js b/lib/web/fetch/data-url.js index 7a74db6bde8..2996feca92a 100644 --- a/lib/web/fetch/data-url.js +++ b/lib/web/fetch/data-url.js @@ -431,7 +431,7 @@ function parseMIMEType (input) { /** @param {string} data */ function forgivingBase64 (data) { // 1. Remove all ASCII whitespace from data. - data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line + data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') let dataLength = data.length // 2. If data’s code point length divides by 4 leaving diff --git a/lib/web/fetch/util.js b/lib/web/fetch/util.js index 8583da1220f..623b475854f 100644 --- a/lib/web/fetch/util.js +++ b/lib/web/fetch/util.js @@ -449,7 +449,7 @@ function determineRequestsReferrer (request) { // 3. Return referrerOrigin. return referrerOrigin } - case 'strict-origin': // eslint-disable-line + case 'strict-origin': /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, diff --git a/package.json b/package.json index 9c560a7b079..049ebca461e 100644 --- a/package.json +++ b/package.json @@ -66,8 +66,8 @@ "prebuild:wasm": "node build/wasm.js --prebuild", "build:wasm": "node build/wasm.js --docker", "generate-pem": "node scripts/generate-pem.js", - "lint": "standard | snazzy", - "lint:fix": "standard --fix | snazzy", + "lint": "eslint --cache", + "lint:fix": "eslint --fix --cache", "test": "npm run test:javascript && cross-env NODE_V8_COVERAGE= npm run test:typescript", "test:javascript": "npm run test:javascript:no-jest && npm run test:jest", "test:javascript:no-jest": "npm run generate-pem && npm run test:unit && npm run test:node-fetch && npm run test:cache && npm run test:interceptors && npm run test:fetch && npm run test:cookies && npm run test:eventsource && npm run test:wpt && npm run test:websocket && npm run test:node-test", @@ -111,6 +111,7 @@ "c8": "^10.0.0", "cross-env": "^7.0.3", "dns-packet": "^5.4.0", + "eslint": "^9.9.0", "fast-check": "^3.17.1", "form-data": "^4.0.0", "formdata-node": "^6.0.3", @@ -118,11 +119,10 @@ "husky": "^9.0.7", "jest": "^29.0.2", "jsdom": "^24.0.0", + "neostandard": "^0.11.2", "node-forge": "^1.3.1", "pre-commit": "^1.2.2", "proxy": "^2.1.1", - "snazzy": "^9.0.0", - "standard": "^17.0.0", "tsd": "^0.31.0", "typescript": "^5.0.2", "ws": "^8.11.0" @@ -130,16 +130,6 @@ "engines": { "node": ">=18.17" }, - "standard": { - "env": [ - "jest" - ], - "ignore": [ - "lib/llhttp/constants.js", - "lib/llhttp/utils.js", - "test/fixtures/wpt" - ] - }, "tsd": { "directory": "test/types", "compilerOptions": { diff --git a/test/fetch/pull-dont-push.js b/test/fetch/pull-dont-push.js index 58eaee3e8fd..27454bd6c58 100644 --- a/test/fetch/pull-dont-push.js +++ b/test/fetch/pull-dont-push.js @@ -46,7 +46,7 @@ test('pull dont\'t push', async (t) => { // consume the stream try { - /* eslint-disable-next-line no-empty, no-unused-vars */ + /* eslint-disable-next-line no-unused-vars */ for await (const chunk of res.body) { // process._rawDebug('chunk', chunk) } diff --git a/test/imports/undici-import.ts b/test/imports/undici-import.ts index ecab8584f6b..776a561c507 100644 --- a/test/imports/undici-import.ts +++ b/test/imports/undici-import.ts @@ -1,10 +1,17 @@ -import { request } from '../../' +import { expectType } from 'tsd' +import { Dispatcher, request } from '../../' import { interceptors } from '../../' -async function exampleCode() { +async function exampleCode () { const retry = interceptors.retry() const rd = interceptors.redirect() const dump = interceptors.dump() + expectType(retry) + expectType(rd) + expectType(dump) + await request('http://localhost:3000/foo') } + +exampleCode() diff --git a/test/jest/mock-agent.test.js b/test/jest/mock-agent.test.js index 6f6bac27bd9..8463fce1ea0 100644 --- a/test/jest/mock-agent.test.js +++ b/test/jest/mock-agent.test.js @@ -3,7 +3,7 @@ const { request, setGlobalDispatcher, MockAgent } = require('../..') const { getResponse } = require('../../lib/mock/mock-utils') -/* global describe, it, expect */ +/* global describe, it, afterEach, expect */ describe('MockAgent', () => { let mockAgent diff --git a/test/node-fetch/headers.js b/test/node-fetch/headers.js index 8500818f354..626722bff91 100644 --- a/test/node-fetch/headers.js +++ b/test/node-fetch/headers.js @@ -303,7 +303,6 @@ describe('Headers', () => { ['a', '3'] ]) - // eslint-disable-next-line quotes assert.strictEqual(format(headers), "{ a: [ '1', '3' ], b: '2', host: 'thehost' }") }) }) diff --git a/test/node-fetch/main.js b/test/node-fetch/main.js index 6b19c3eb4be..2360620740c 100644 --- a/test/node-fetch/main.js +++ b/test/node-fetch/main.js @@ -1438,6 +1438,8 @@ describe('node-fetch', () => { ) }) + /* global expect */ + // TODO: fix test. it.skip('should timeout on cloning response without consuming one of the streams when the second packet size is equal default highWaterMark', { timeout: 300 }, function () { const url = local.mockState(res => { diff --git a/test/node-test/abort-controller.js b/test/node-test/abort-controller.js index b71ffa7abf7..6db151e5d16 100644 --- a/test/node-test/abort-controller.js +++ b/test/node-test/abort-controller.js @@ -158,7 +158,7 @@ for (const { AbortControllerImpl, controllerName } of controllers) { await p.completed }) - function waitingWithBody (body, type) { // eslint-disable-line + function waitingWithBody (body, type) { test(`Abort ${controllerName} while waiting response (with body ${type})`, async (t) => { const p = tspl(t, { plan: 1 }) @@ -187,7 +187,7 @@ for (const { AbortControllerImpl, controllerName } of controllers) { waitingWithBody(new Uint8Array([42]), 'Uint8Array') waitingWithBody(wrapWithAsyncIterable(createReadStream(__filename)), 'async-iterator') - function writeHeadersStartedWithBody (body, type) { // eslint-disable-line + function writeHeadersStartedWithBody (body, type) { test(`Abort ${controllerName} while waiting response (write headers started) (with body ${type})`, async (t) => { const p = tspl(t, { plan: 1 }) @@ -217,7 +217,7 @@ for (const { AbortControllerImpl, controllerName } of controllers) { writeHeadersStartedWithBody(new Uint8Array([42]), 'Uint8Array') writeHeadersStartedWithBody(wrapWithAsyncIterable(createReadStream(__filename)), 'async-iterator') - function writeBodyStartedWithBody (body, type) { // eslint-disable-line + function writeBodyStartedWithBody (body, type) { test(`Abort ${controllerName} while waiting response (write headers and write body started) (with body ${type})`, async (t) => { const p = tspl(t, { plan: 2 }) diff --git a/test/node-test/balanced-pool.js b/test/node-test/balanced-pool.js index d51d4a5cbb2..eb9ab05b936 100644 --- a/test/node-test/balanced-pool.js +++ b/test/node-test/balanced-pool.js @@ -202,7 +202,7 @@ test('factory option with basic get request', async (t) => { } } - const client = new BalancedPool([], opts) // eslint-disable-line + const client = new BalancedPool([], opts) let serverCalled = 0 const server = createServer((req, res) => { diff --git a/test/node-test/client-errors.js b/test/node-test/client-errors.js index 3ac832b1635..d53e9ffc146 100644 --- a/test/node-test/client-errors.js +++ b/test/node-test/client-errors.js @@ -312,7 +312,7 @@ test('invalid options throws', (t, done) => { try { new Client(new URL('http://localhost:200'), { // eslint-disable-line keepAliveTimeout: 'asd' - }) // eslint-disable-line + }) assert.ok(0) } catch (err) { assert.ok(err instanceof errors.InvalidArgumentError) @@ -322,7 +322,7 @@ test('invalid options throws', (t, done) => { try { new Client(new URL('http://localhost:200'), { // eslint-disable-line localAddress: 123 - }) // eslint-disable-line + }) assert.ok(0) } catch (err) { assert.ok(err instanceof errors.InvalidArgumentError) @@ -332,7 +332,7 @@ test('invalid options throws', (t, done) => { try { new Client(new URL('http://localhost:200'), { // eslint-disable-line localAddress: 'abcd123' - }) // eslint-disable-line + }) assert.ok(0) } catch (err) { assert.ok(err instanceof errors.InvalidArgumentError) @@ -342,7 +342,7 @@ test('invalid options throws', (t, done) => { try { new Client(new URL('http://localhost:200'), { // eslint-disable-line keepAliveMaxTimeout: 'asd' - }) // eslint-disable-line + }) assert.ok(0) } catch (err) { assert.ok(err instanceof errors.InvalidArgumentError) @@ -352,7 +352,7 @@ test('invalid options throws', (t, done) => { try { new Client(new URL('http://localhost:200'), { // eslint-disable-line keepAliveMaxTimeout: 0 - }) // eslint-disable-line + }) assert.ok(0) } catch (err) { assert.ok(err instanceof errors.InvalidArgumentError) @@ -362,7 +362,7 @@ test('invalid options throws', (t, done) => { try { new Client(new URL('http://localhost:200'), { // eslint-disable-line keepAliveTimeoutThreshold: 'asd' - }) // eslint-disable-line + }) assert.ok(0) } catch (err) { assert.ok(err instanceof errors.InvalidArgumentError) @@ -408,7 +408,7 @@ test('invalid options throws', (t, done) => { } try { - const client = new Client(new URL('http://localhost:200')) // eslint-disable-line + const client = new Client(new URL('http://localhost:200')) client.destroy(null, null) assert.ok(0) } catch (err) { @@ -417,7 +417,7 @@ test('invalid options throws', (t, done) => { } try { - const client = new Client(new URL('http://localhost:200')) // eslint-disable-line + const client = new Client(new URL('http://localhost:200')) client.close(null, null) assert.ok(0) } catch (err) { diff --git a/test/types/agent.test-d.ts b/test/types/agent.test-d.ts index 5c12c480018..72e27293418 100644 --- a/test/types/agent.test-d.ts +++ b/test/types/agent.test-d.ts @@ -17,7 +17,7 @@ expectAssignable(new Agent({ factory: () => new Dispatcher() })) // request expectAssignable>(agent.request({ origin: '', path: '', method: 'GET' })) - expectAssignable>(agent.request({ origin: '', path: '', method: 'GET', onInfo: ((info) => {}) })) + expectAssignable>(agent.request({ origin: '', path: '', method: 'GET', onInfo: (info) => {} })) expectAssignable>(agent.request({ origin: new URL('http://localhost'), path: '', method: 'GET' })) expectAssignable(agent.request({ origin: '', path: '', method: 'GET' }, (err, data) => { expectAssignable(err) @@ -33,7 +33,7 @@ expectAssignable(new Agent({ factory: () => new Dispatcher() })) expectAssignable(data) return new Writable() })) - expectAssignable>(agent.stream({ origin: '', path: '', method: 'GET', onInfo: ((info) => {}) }, data => { + expectAssignable>(agent.stream({ origin: '', path: '', method: 'GET', onInfo: (info) => {} }, data => { expectAssignable(data) return new Writable() })) @@ -69,7 +69,7 @@ expectAssignable(new Agent({ factory: () => new Dispatcher() })) expectAssignable(data) return new Readable() })) - expectAssignable(agent.pipeline({ origin: '', path: '', method: 'GET', onInfo: ((info) => {}) }, data => { + expectAssignable(agent.pipeline({ origin: '', path: '', method: 'GET', onInfo: (info) => {} }, data => { expectAssignable(data) return new Readable() })) diff --git a/test/types/balanced-pool.test-d.ts b/test/types/balanced-pool.test-d.ts index d7ccf7be8d4..abbdf19ae60 100644 --- a/test/types/balanced-pool.test-d.ts +++ b/test/types/balanced-pool.test-d.ts @@ -10,7 +10,7 @@ expectAssignable(new BalancedPool('', { factory: () => new Dispatc expectAssignable(new BalancedPool('', { factory: (origin, opts) => new Client(origin, opts) })) expectAssignable(new BalancedPool('', { connections: 1 })) expectAssignable(new BalancedPool(['http://localhost:4242', 'http://www.nodejs.org'])) -expectAssignable(new BalancedPool([new URL('http://localhost:4242'),new URL('http://www.nodejs.org')], {})) +expectAssignable(new BalancedPool([new URL('http://localhost:4242'), new URL('http://www.nodejs.org')], {})) { const pool = new BalancedPool('', {}) @@ -26,7 +26,6 @@ expectAssignable(new BalancedPool([new URL('http://localhost:4242' expectAssignable(pool.removeUpstream(new URL('http://www.nodejs.org'))) expectAssignable(pool.upstreams) - // request expectAssignable>(pool.request({ origin: '', path: '', method: 'GET' })) expectAssignable>(pool.request({ origin: new URL('http://localhost'), path: '', method: 'GET' })) diff --git a/test/types/client.test-d.ts b/test/types/client.test-d.ts index c416d779bec..1c0f558a790 100644 --- a/test/types/client.test-d.ts +++ b/test/types/client.test-d.ts @@ -16,71 +16,69 @@ expectAssignable(new Client(new URL('http://localhost'), {})) /** * Tests for Client.Options: */ -{ - expectAssignable(new Client('', { - maxHeaderSize: 16384 - })) - expectAssignable(new Client('', { - headersTimeout: 300e3 - })) - expectAssignable(new Client('', { - connectTimeout: 300e3 - })) - expectAssignable(new Client('', { - bodyTimeout: 300e3 - })) - expectAssignable(new Client('', { - keepAliveTimeout: 4e3 - })) - expectAssignable(new Client('', { - keepAliveMaxTimeout: 600e3 - })) - expectAssignable(new Client('', { - keepAliveTimeoutThreshold: 1e3 - })) - expectAssignable(new Client('', { - socketPath: '/var/run/docker.sock' - })) - expectAssignable(new Client('', { - pipelining: 1 - })) - expectAssignable(new Client('', { - strictContentLength: true - })) - expectAssignable(new Client('', { - maxCachedSessions: 1 - })) - expectAssignable(new Client('', { - maxRedirections: 1 - })) - expectAssignable(new Client('', { - maxRequestsPerClient: 1 - })) - expectAssignable(new Client('', { - localAddress: '127.0.0.1' - })) - expectAssignable(new Client('', { - maxResponseSize: -1 - })) - expectAssignable(new Client('', { - autoSelectFamily: true - })) - expectAssignable(new Client('', { - autoSelectFamilyAttemptTimeout: 300e3 - })) - expectAssignable(new Client('', { - interceptors: { - Client: [(dispatcher) => { - expectAssignable(dispatcher); - return (opts, handlers) => { - expectAssignable(opts); - expectAssignable(handlers); - return dispatcher(opts, handlers) - } - }] - } - })) -} +expectAssignable(new Client('', { + maxHeaderSize: 16384 +})) +expectAssignable(new Client('', { + headersTimeout: 300e3 +})) +expectAssignable(new Client('', { + connectTimeout: 300e3 +})) +expectAssignable(new Client('', { + bodyTimeout: 300e3 +})) +expectAssignable(new Client('', { + keepAliveTimeout: 4e3 +})) +expectAssignable(new Client('', { + keepAliveMaxTimeout: 600e3 +})) +expectAssignable(new Client('', { + keepAliveTimeoutThreshold: 1e3 +})) +expectAssignable(new Client('', { + socketPath: '/var/run/docker.sock' +})) +expectAssignable(new Client('', { + pipelining: 1 +})) +expectAssignable(new Client('', { + strictContentLength: true +})) +expectAssignable(new Client('', { + maxCachedSessions: 1 +})) +expectAssignable(new Client('', { + maxRedirections: 1 +})) +expectAssignable(new Client('', { + maxRequestsPerClient: 1 +})) +expectAssignable(new Client('', { + localAddress: '127.0.0.1' +})) +expectAssignable(new Client('', { + maxResponseSize: -1 +})) +expectAssignable(new Client('', { + autoSelectFamily: true +})) +expectAssignable(new Client('', { + autoSelectFamilyAttemptTimeout: 300e3 +})) +expectAssignable(new Client('', { + interceptors: { + Client: [(dispatcher) => { + expectAssignable(dispatcher) + return (opts, handlers) => { + expectAssignable(opts) + expectAssignable(handlers) + return dispatcher(opts, handlers) + } + }] + } +})) { const client = new Client('') diff --git a/test/types/connector.test-d.ts b/test/types/connector.test-d.ts index 923656974d1..f8d8d8b55de 100644 --- a/test/types/connector.test-d.ts +++ b/test/types/connector.test-d.ts @@ -1,8 +1,7 @@ -import {expectAssignable} from 'tsd' +import { expectAssignable } from 'tsd' import { Client, buildConnector } from '../..' -import {ConnectionOptions, TLSSocket} from 'tls' -import {Socket} from 'net' -import {IpcNetConnectOpts, NetConnectOpts, TcpNetConnectOpts} from "net"; +import { TLSSocket } from 'tls' +import { Socket } from 'net' const connector = buildConnector({ rejectUnauthorized: false, allowH2: false }) expectAssignable(new Client('', { @@ -26,13 +25,13 @@ expectAssignable({ checkServerIdentity: () => undefined, // Test if ConnectionOptions is assignable localPort: 1234, // Test if TcpNetConnectOpts is assignable keepAlive: true, - keepAliveInitialDelay: 12345, -}); + keepAliveInitialDelay: 12345 +}) expectAssignable({ - protocol: "http", - hostname: "example.com", - port: "", - localAddress: "127.0.0.1", - httpSocket: new Socket(), -}); + protocol: 'http', + hostname: 'example.com', + port: '', + localAddress: '127.0.0.1', + httpSocket: new Socket() +}) diff --git a/test/types/diagnostics-channel.test-d.ts b/test/types/diagnostics-channel.test-d.ts index 334404c385f..3e51e0adbbe 100644 --- a/test/types/diagnostics-channel.test-d.ts +++ b/test/types/diagnostics-channel.test-d.ts @@ -1,72 +1,72 @@ -import { Socket } from "net"; -import { expectAssignable } from "tsd"; -import { DiagnosticsChannel, buildConnector } from "../.."; +import { Socket } from 'net' +import { expectAssignable } from 'tsd' +import { DiagnosticsChannel, buildConnector } from '../..' const request = { - origin: "", + origin: '', completed: true, - method: "GET" as const, - path: "", - headers: "", + method: 'GET' as const, + path: '', + headers: '', addHeader: (key: string, value: string) => { - return request; - }, -}; + return request + } +} const response = { statusCode: 200, - statusText: "OK", - headers: [Buffer.from(""), Buffer.from("")], -}; + statusText: 'OK', + headers: [Buffer.from(''), Buffer.from('')] +} const connectParams = { - host: "", - hostname: "", - protocol: "", - port: "", - servername: "", -}; + host: '', + hostname: '', + protocol: '', + port: '', + servername: '' +} -expectAssignable({ request }); -expectAssignable({ request }); +expectAssignable({ request }) +expectAssignable({ request }) expectAssignable({ request, - response, -}); + response +}) expectAssignable({ request, - trailers: [Buffer.from(""), Buffer.from("")], -}); + trailers: [Buffer.from(''), Buffer.from('')] +}) expectAssignable({ request, - error: new Error("Error"), -}); + error: new Error('Error') +}) expectAssignable({ request, - headers: "", - socket: new Socket(), -}); + headers: '', + socket: new Socket() +}) expectAssignable({ connectParams, connector: ( options: buildConnector.Options, callback: buildConnector.Callback - ) => new Socket(), -}); + ) => new Socket() +}) expectAssignable({ socket: new Socket(), connectParams, connector: ( options: buildConnector.Options, callback: buildConnector.Callback - ) => new Socket(), -}); + ) => new Socket() +}) expectAssignable({ - error: new Error("Error"), + error: new Error('Error'), socket: new Socket(), connectParams, connector: ( options: buildConnector.Options, callback: buildConnector.Callback - ) => new Socket(), -}); + ) => new Socket() +}) diff --git a/test/types/dispatcher.events.test-d.ts b/test/types/dispatcher.events.test-d.ts index 71057e7a182..2980eb1ce6b 100644 --- a/test/types/dispatcher.events.test-d.ts +++ b/test/types/dispatcher.events.test-d.ts @@ -1,7 +1,7 @@ import { Dispatcher } from '../..' -import {expectAssignable} from "tsd"; -import {URL} from "url"; -import Errors from "../../types/errors"; +import { expectAssignable } from 'tsd' +import { URL } from 'url' +import Errors from '../../types/errors' interface EventHandler { connect(origin: URL, targets: readonly Dispatcher[]): void @@ -24,14 +24,14 @@ interface EventHandler { expectAssignable(dispatcher.listeners('connectionError')) expectAssignable(dispatcher.listeners('drain')) - const eventHandlerMethods: ['on', 'once', 'off', 'addListener', "removeListener", "prependListener", "prependOnceListener"] - = ['on', 'once', 'off', 'addListener', "removeListener", "prependListener", "prependOnceListener"] + const eventHandlerMethods: ['on', 'once', 'off', 'addListener', 'removeListener', 'prependListener', 'prependOnceListener'] = + ['on', 'once', 'off', 'addListener', 'removeListener', 'prependListener', 'prependOnceListener'] for (const method of eventHandlerMethods) { - expectAssignable(dispatcher[method]('connect', eventHandler["connect"])) - expectAssignable(dispatcher[method]('disconnect', eventHandler["disconnect"])) - expectAssignable(dispatcher[method]('connectionError', eventHandler["connectionError"])) - expectAssignable(dispatcher[method]('drain', eventHandler["drain"])) + expectAssignable(dispatcher[method]('connect', eventHandler['connect'])) + expectAssignable(dispatcher[method]('disconnect', eventHandler['disconnect'])) + expectAssignable(dispatcher[method]('connectionError', eventHandler['connectionError'])) + expectAssignable(dispatcher[method]('drain', eventHandler['drain'])) } const origin = new URL('') @@ -42,4 +42,3 @@ interface EventHandler { expectAssignable(dispatcher.emit('connectionError', origin, targets, error)) expectAssignable(dispatcher.emit('drain', origin)) } - diff --git a/test/types/dispatcher.test-d.ts b/test/types/dispatcher.test-d.ts index 1c84ed01443..58dda692fdc 100644 --- a/test/types/dispatcher.test-d.ts +++ b/test/types/dispatcher.test-d.ts @@ -12,13 +12,13 @@ expectAssignable(new Dispatcher()) const nodeCoreHeaders = { authorization: undefined, - ['content-type']: 'application/json' - } satisfies IncomingHttpHeaders; + 'content-type': 'application/json' + } satisfies IncomingHttpHeaders const headerInstanceHeaders = new Headers({ hello: 'world' }) const mapHeaders = new Map([['hello', 'world']]) const iteratorHeaders = { - *[Symbol.iterator]() { + * [Symbol.iterator] () { yield ['hello', 'world'] } } @@ -35,7 +35,7 @@ expectAssignable(new Dispatcher()) expectAssignable(dispatcher.dispatch({ origin: '', path: '', method: 'GET', headers: mapHeaders, reset: true }, {})) expectAssignable(dispatcher.dispatch({ origin: '', path: '', method: 'GET', headers: iteratorHeaders, reset: true }, {})) expectAssignable(dispatcher.dispatch({ origin: new URL('http://localhost'), path: '', method: 'GET' }, {})) - expectAssignable(dispatcher.dispatch({ path: '', method: "CUSTOM" }, {})) + expectAssignable(dispatcher.dispatch({ path: '', method: 'CUSTOM' }, {})) // connect expectAssignable>(dispatcher.connect({ origin: '', path: '', maxRedirections: 0 })) @@ -102,9 +102,9 @@ expectAssignable(new Dispatcher()) return new Writable() })) expectAssignable>>(dispatcher.stream({ origin: '', path: '', method: 'GET', opaque: { example: '' } }, data => { - expectType<{ example: string }>(data.opaque); - return new Writable(); - })); + expectType<{ example: string }>(data.opaque) + return new Writable() + })) expectAssignable(dispatcher.stream( { origin: '', path: '', method: 'GET', reset: false }, data => { @@ -170,47 +170,43 @@ expectAssignable(new Dispatcher()) expectAssignable(dispatcher.destroy(null, () => {})) } -declare const { body }: Dispatcher.ResponseData; +declare const { body }: Dispatcher.ResponseData // compose -{ - expectAssignable(new Dispatcher().compose( - (dispatcher) => { - expectAssignable(dispatcher); - return (opts, handlers) => { - expectAssignable(opts); - expectAssignable(handlers); - return dispatcher(opts, handlers) - } +expectAssignable(new Dispatcher().compose( + (dispatcher) => { + expectAssignable(dispatcher) + return (opts, handlers) => { + expectAssignable(opts) + expectAssignable(handlers) + return dispatcher(opts, handlers) } - )) - expectAssignable(new Dispatcher().compose([ - (dispatcher) => { - expectAssignable(dispatcher); - return (opts, handlers) => { - expectAssignable(opts); - expectAssignable(handlers); - return dispatcher(opts, handlers) - } - }, - (dispatcher) => { - expectAssignable(dispatcher); - return (opts, handlers) => { - expectAssignable(opts); - expectAssignable(handlers); - return dispatcher(opts, handlers) - } + } +)) +expectAssignable(new Dispatcher().compose([ + (dispatcher) => { + expectAssignable(dispatcher) + return (opts, handlers) => { + expectAssignable(opts) + expectAssignable(handlers) + return dispatcher(opts, handlers) } - ])) -} + }, + (dispatcher) => { + expectAssignable(dispatcher) + return (opts, handlers) => { + expectAssignable(opts) + expectAssignable(handlers) + return dispatcher(opts, handlers) + } + } +])) -{ - // body mixin tests - expectType(body.body) - expectType(body.bodyUsed) - expectType>(body.arrayBuffer()) - expectType>(body.blob()) - expectType>(body.formData()) - expectType>(body.text()) - expectType>(body.json()) -} +// body mixin tests +expectType(body.body) +expectType(body.bodyUsed) +expectType>(body.arrayBuffer()) +expectType>(body.blob()) +expectType>(body.formData()) +expectType>(body.text()) +expectType>(body.json()) diff --git a/test/types/env-http-proxy-agent.test-d.ts b/test/types/env-http-proxy-agent.test-d.ts index c08a720e301..e6370e4418a 100644 --- a/test/types/env-http-proxy-agent.test-d.ts +++ b/test/types/env-http-proxy-agent.test-d.ts @@ -12,7 +12,7 @@ expectAssignable(new EnvHttpProxyAgent({ httpProxy: 'http://l // request expectAssignable>(agent.request({ origin: '', path: '', method: 'GET' })) - expectAssignable>(agent.request({ origin: '', path: '', method: 'GET', onInfo: ((info) => {}) })) + expectAssignable>(agent.request({ origin: '', path: '', method: 'GET', onInfo: (info) => {} })) expectAssignable>(agent.request({ origin: new URL('http://localhost'), path: '', method: 'GET' })) expectAssignable(agent.request({ origin: '', path: '', method: 'GET' }, (err, data) => { expectAssignable(err) @@ -28,7 +28,7 @@ expectAssignable(new EnvHttpProxyAgent({ httpProxy: 'http://l expectAssignable(data) return new Writable() })) - expectAssignable>(agent.stream({ origin: '', path: '', method: 'GET', onInfo: ((info) => {}) }, data => { + expectAssignable>(agent.stream({ origin: '', path: '', method: 'GET', onInfo: (info) => {} }, data => { expectAssignable(data) return new Writable() })) @@ -64,7 +64,7 @@ expectAssignable(new EnvHttpProxyAgent({ httpProxy: 'http://l expectAssignable(data) return new Readable() })) - expectAssignable(agent.pipeline({ origin: '', path: '', method: 'GET', onInfo: ((info) => {}) }, data => { + expectAssignable(agent.pipeline({ origin: '', path: '', method: 'GET', onInfo: (info) => {} }, data => { expectAssignable(data) return new Readable() })) diff --git a/test/types/errors.test-d.ts b/test/types/errors.test-d.ts index e6b20251fed..df04775cb02 100644 --- a/test/types/errors.test-d.ts +++ b/test/types/errors.test-d.ts @@ -1,7 +1,7 @@ import { expectAssignable } from 'tsd' import { errors } from '../..' import Client from '../../types/client' -import { IncomingHttpHeaders } from "../../types/header"; +import { IncomingHttpHeaders } from '../../types/header' expectAssignable(new errors.UndiciError()) expectAssignable(new errors.UndiciError().name) @@ -113,7 +113,7 @@ expectAssignable<'UND_ERR_PRX_TLS'>(new errors.SecureProxyConnectionError().code { // @ts-ignore - function f (): errors.HeadersTimeoutError | errors.ConnectTimeoutError { return } + function f (): errors.HeadersTimeoutError | errors.ConnectTimeoutError { } const e = f() diff --git a/test/types/event-source-d.ts b/test/types/event-source-d.ts index 9a3cc8c31af..92b2628ee19 100644 --- a/test/types/event-source-d.ts +++ b/test/types/event-source-d.ts @@ -15,7 +15,7 @@ expectType(new EventSource('https://example.com')) expectType(new EventSource(new URL('https://example.com'))) expectType(new EventSource('https://example.com', {})) expectType(new EventSource('https://example.com', { - withCredentials: true, + withCredentials: true })) expectAssignable({ dispatcher: agent }) diff --git a/test/types/fetch.test-d.ts b/test/types/fetch.test-d.ts index 8c878e5226b..68d69c0f4ab 100644 --- a/test/types/fetch.test-d.ts +++ b/test/types/fetch.test-d.ts @@ -20,7 +20,8 @@ import { Response, ResponseInit, ResponseType, - ReferrerPolicy + ReferrerPolicy, + Dispatcher } from '../..' const requestInit: RequestInit = {} @@ -46,10 +47,14 @@ expectType(requestInit.integrity) expectType(requestInit.signal) expectType(requestInit.credentials) expectType(requestInit.mode) -expectType(requestInit.referrer); +expectType(requestInit.referrer) expectType(requestInit.referrerPolicy) expectType(requestInit.window) +expectType(requestInit2.dispatcher) + +expectType(requestInit4.body) + expectType(responseInit.status) expectType(responseInit.statusText) expectType(responseInit.headers) @@ -60,7 +65,7 @@ expectType(new Headers([])) expectType(new Headers(headers)) expectType(new Headers(undefined)) -expectAssignable({ 'a': 'b' } as Record) +expectAssignable({ a: 'b' } as Record) expectAssignable({ 'content-type': 'application/gzip' } satisfies HeadersInit) expectAssignable({ 'Content-Type': 'nonstandard/mime' } satisfies HeadersInit) expectNotAssignable([['1', '2', '3']]) diff --git a/test/types/global-dispatcher.test-d.ts b/test/types/global-dispatcher.test-d.ts index 428b80911d3..18f4bac2621 100644 --- a/test/types/global-dispatcher.test-d.ts +++ b/test/types/global-dispatcher.test-d.ts @@ -7,6 +7,4 @@ import { setGlobalDispatcher, Dispatcher, getGlobalDispatcher } from '../..' expectAssignable(setGlobalDispatcher(new CustomDispatcher())) } -{ - expectAssignable(getGlobalDispatcher()) -} +expectAssignable(getGlobalDispatcher()) diff --git a/test/types/header.test-d.ts b/test/types/header.test-d.ts index 38ac9f6afdc..b5fbceb43bb 100644 --- a/test/types/header.test-d.ts +++ b/test/types/header.test-d.ts @@ -1,16 +1,16 @@ -import { IncomingHttpHeaders as CoreIncomingHttpHeaders } from "http"; -import { expectAssignable, expectNotAssignable } from "tsd"; -import { IncomingHttpHeaders } from "../../types/header"; +import { IncomingHttpHeaders as CoreIncomingHttpHeaders } from 'http' +import { expectAssignable, expectNotAssignable } from 'tsd' +import { IncomingHttpHeaders } from '../../types/header' const headers = { authorization: undefined, - ["content-type"]: "application/json", -} satisfies CoreIncomingHttpHeaders; + 'content-type': 'application/json' +} satisfies CoreIncomingHttpHeaders -expectAssignable(headers); +expectAssignable(headers) // It is why we do not need to add ` | null` to `IncomingHttpHeaders`: expectNotAssignable({ authorization: null, - ["content-type"]: "application/json", -}); + 'content-type': 'application/json' +}) diff --git a/test/types/index.test-d.ts b/test/types/index.test-d.ts index c4d0244f04a..8fe57aba5e9 100644 --- a/test/types/index.test-d.ts +++ b/test/types/index.test-d.ts @@ -1,6 +1,6 @@ import { expectAssignable } from 'tsd' -import Undici, {Pool, Client, errors, fetch, Interceptable, RedirectHandler, DecoratorHandler, Headers, Response, Request, FormData} from '../..' -import Dispatcher from "../../types/dispatcher"; +import Undici, { Pool, Client, errors, fetch, Interceptable, RedirectHandler, Headers, Response, Request, FormData } from '../..' +import Dispatcher from '../../types/dispatcher' expectAssignable(new Undici.Pool('', {})) expectAssignable(new Undici.Client('', {})) @@ -16,9 +16,9 @@ expectAssignable(Undici.interceptors.re expectAssignable(Undici.interceptors.retry()) const client = new Undici.Client('', {}) -const handler: Dispatcher.DispatchHandlers = {} +const handler: Dispatcher.DispatchHandlers = {} const redirectHandler = new Undici.RedirectHandler(client, 10, { path: '/', method: 'GET' -}, handler, false) as RedirectHandler; -expectAssignable(redirectHandler); +}, handler, false) as RedirectHandler +expectAssignable(redirectHandler) diff --git a/test/types/interceptor.test-d.ts b/test/types/interceptor.test-d.ts index ba242bfcadb..fa87fe1e6a4 100644 --- a/test/types/interceptor.test-d.ts +++ b/test/types/interceptor.test-d.ts @@ -1,5 +1,5 @@ -import {expectAssignable} from "tsd"; -import Undici from "../.."; -import Dispatcher from "../../types/dispatcher"; +import { expectAssignable } from 'tsd' +import Undici from '../..' +import Dispatcher from '../../types/dispatcher' expectAssignable(Undici.createRedirectInterceptor({ maxRedirections: 3 })) diff --git a/test/types/mock-agent.test-d.ts b/test/types/mock-agent.test-d.ts index 5f7f9686494..c1930db9edf 100644 --- a/test/types/mock-agent.test-d.ts +++ b/test/types/mock-agent.test-d.ts @@ -1,7 +1,7 @@ -import {expectAssignable, expectType} from 'tsd' -import {Agent, Dispatcher, MockAgent, MockClient, MockPool, setGlobalDispatcher} from '../..' -import {MockInterceptor} from '../../types/mock-interceptor' -import MockDispatch = MockInterceptor.MockDispatch; +import { expectAssignable, expectType } from 'tsd' +import { Agent, Dispatcher, MockAgent, MockClient, MockPool, setGlobalDispatcher } from '../..' +import { MockInterceptor } from '../../types/mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch expectAssignable(new MockAgent()) expectAssignable(new MockAgent({})) @@ -12,6 +12,7 @@ expectAssignable(new MockAgent({})) // get expectAssignable(mockAgent.get('')) + // eslint-disable-next-line prefer-regex-literals expectAssignable(mockAgent.get(new RegExp(''))) expectAssignable(mockAgent.get((origin) => { expectAssignable(origin) @@ -31,6 +32,7 @@ expectAssignable(new MockAgent({})) // enableNetConnect expectAssignable(mockAgent.enableNetConnect()) expectAssignable(mockAgent.enableNetConnect('')) + // eslint-disable-next-line prefer-regex-literals expectAssignable(mockAgent.enableNetConnect(new RegExp(''))) expectAssignable(mockAgent.enableNetConnect((host) => { expectAssignable(host) @@ -41,21 +43,21 @@ expectAssignable(new MockAgent({})) expectAssignable(mockAgent.disableNetConnect()) // dispatch - expectAssignable(mockAgent.dispatch({origin: '', path: '', method: 'GET'}, {})) + expectAssignable(mockAgent.dispatch({ origin: '', path: '', method: 'GET' }, {})) // intercept - expectAssignable((mockAgent.get('foo')).intercept({path: '', method: 'GET'})) + expectAssignable((mockAgent.get('foo')).intercept({ path: '', method: 'GET' })) } { - const mockAgent = new MockAgent({connections: 1}) + const mockAgent = new MockAgent({ connections: 1 }) expectAssignable(setGlobalDispatcher(mockAgent)) expectAssignable(mockAgent.get('')) } { const agent = new Agent() - const mockAgent = new MockAgent({agent}) + const mockAgent = new MockAgent({ agent }) expectAssignable(setGlobalDispatcher(mockAgent)) expectAssignable(mockAgent.get('')) } @@ -65,7 +67,7 @@ expectAssignable(new MockAgent({})) origin: string; } - const agent = new MockAgent({agent: new Agent()}) + const agent = new MockAgent({ agent: new Agent() }) expectType<() => PendingInterceptor[]>(agent.pendingInterceptors) expectType<(options?: { pendingInterceptorsFormatter?: { diff --git a/test/types/mock-client.test-d.ts b/test/types/mock-client.test-d.ts index 9e92b8ec1ec..cc9fabfa423 100644 --- a/test/types/mock-client.test-d.ts +++ b/test/types/mock-client.test-d.ts @@ -9,6 +9,7 @@ import { MockInterceptor } from '../../types/mock-interceptor' expectAssignable(mockClient.intercept({ path: '', method: 'GET' })) expectAssignable(mockClient.intercept({ path: '', method: 'GET', body: '', headers: { 'User-Agent': '' } })) expectAssignable(mockClient.intercept({ path: '', method: 'GET', query: { id: 1 } })) + // eslint-disable-next-line prefer-regex-literals expectAssignable(mockClient.intercept({ path: new RegExp(''), method: new RegExp(''), body: new RegExp(''), headers: { 'User-Agent': new RegExp('') } })) expectAssignable(mockClient.intercept({ path: (path) => { @@ -38,6 +39,4 @@ import { MockInterceptor } from '../../types/mock-interceptor' expectAssignable>(mockClient.close()) } -{ - expectAssignable(new MockClient('', {agent: new MockAgent({ connections: 1})})) -} +expectAssignable(new MockClient('', { agent: new MockAgent({ connections: 1 }) })) diff --git a/test/types/mock-errors.test-d.ts b/test/types/mock-errors.test-d.ts index 2cf3e5e6129..d02843aad3a 100644 --- a/test/types/mock-errors.test-d.ts +++ b/test/types/mock-errors.test-d.ts @@ -9,7 +9,7 @@ expectAssignable<'UND_MOCK_ERR_MOCK_NOT_MATCHED'>(new mockErrors.MockNotMatchedE { // @ts-ignore - function f (): mockErrors.MockNotMatchedError { return } + function f (): mockErrors.MockNotMatchedError { } const e = f() diff --git a/test/types/mock-interceptor.test-d.ts b/test/types/mock-interceptor.test-d.ts index d246e2600a7..5c351d28112 100644 --- a/test/types/mock-interceptor.test-d.ts +++ b/test/types/mock-interceptor.test-d.ts @@ -1,8 +1,8 @@ -import { expectAssignable } from 'tsd' +import { expectAssignable, expectType } from 'tsd' import { MockAgent, MockPool, BodyInit, Dispatcher } from '../..' import { MockInterceptor, MockScope } from '../../types/mock-interceptor' -declare const mockResponseCallbackOptions: MockInterceptor.MockResponseCallbackOptions; +declare const mockResponseCallbackOptions: MockInterceptor.MockResponseCallbackOptions expectAssignable(mockResponseCallbackOptions.body) @@ -11,6 +11,8 @@ expectAssignable(mockResponseCall const mockInterceptor = mockPool.intercept({ path: '', method: 'GET' }) const mockInterceptorDefaultMethod = mockPool.intercept({ path: '' }) + expectType(mockInterceptorDefaultMethod) + // reply expectAssignable(mockInterceptor.reply(200)) expectAssignable(mockInterceptor.reply(200, '')) @@ -19,36 +21,44 @@ expectAssignable(mockResponseCall expectAssignable(mockInterceptor.reply(200, () => ({}))) expectAssignable(mockInterceptor.reply(200, {}, {})) expectAssignable(mockInterceptor.reply(200, () => ({}), {})) - expectAssignable(mockInterceptor.reply(200, {}, { headers: { foo: 'bar' }})) - expectAssignable(mockInterceptor.reply(200, () => ({}), { headers: { foo: 'bar' }})) - expectAssignable(mockInterceptor.reply(200, {}, { trailers: { foo: 'bar' }})) - expectAssignable(mockInterceptor.reply(200, () => ({}), { trailers: { foo: 'bar' }})) + expectAssignable(mockInterceptor.reply(200, {}, { headers: { foo: 'bar' } })) + expectAssignable(mockInterceptor.reply(200, () => ({}), { headers: { foo: 'bar' } })) + expectAssignable(mockInterceptor.reply(200, {}, { trailers: { foo: 'bar' } })) + expectAssignable(mockInterceptor.reply(200, () => ({}), { trailers: { foo: 'bar' } })) expectAssignable>(mockInterceptor.reply<{ foo: string }>(200, { foo: 'bar' })) expectAssignable>(mockInterceptor.reply<{ foo: string }>(200, () => ({ foo: 'bar' }))) - expectAssignable(mockInterceptor.reply(() => ({ statusCode: 200, data: { foo: 'bar' }}))) - expectAssignable(mockInterceptor.reply(() => ({ statusCode: 200, data: { foo: 'bar' }, responseOptions: { - headers: { foo: 'bar' } - }}))) + expectAssignable(mockInterceptor.reply(() => ({ statusCode: 200, data: { foo: 'bar' } }))) + expectAssignable(mockInterceptor.reply(() => ({ + statusCode: 200, + data: { foo: 'bar' }, + responseOptions: { + headers: { foo: 'bar' } + } + }))) expectAssignable(mockInterceptor.reply((options) => { - expectAssignable(options); - return { statusCode: 200, data: { foo: 'bar'} - }})) - expectAssignable(mockInterceptor.reply(() => ({ statusCode: 200, data: { foo: 'bar' }, responseOptions: { - trailers: { foo: 'bar' } - }}))) + expectAssignable(options) + return { statusCode: 200, data: { foo: 'bar' } } + })) + expectAssignable(mockInterceptor.reply(() => ({ + statusCode: 200, + data: { foo: 'bar' }, + responseOptions: { + trailers: { foo: 'bar' } + } + }))) mockInterceptor.reply((options) => { - expectAssignable(options.path); - expectAssignable(options.method); - expectAssignable(options.headers); - expectAssignable(options.origin); - expectAssignable(options.body); - expectAssignable(options.maxRedirections); + expectAssignable(options.path) + expectAssignable(options.method) + expectAssignable(options.headers) + expectAssignable(options.origin) + expectAssignable(options.body) + expectAssignable(options.maxRedirections) return { statusCode: 200, data: { foo: 'bar' } } }) // replyWithError class CustomError extends Error { - hello(): void {} + hello (): void {} } expectAssignable(mockInterceptor.replyWithError(new Error(''))) expectAssignable(mockInterceptor.replyWithError(new CustomError(''))) diff --git a/test/types/mock-pool.test-d.ts b/test/types/mock-pool.test-d.ts index b51779bf3e0..b2202f6486d 100644 --- a/test/types/mock-pool.test-d.ts +++ b/test/types/mock-pool.test-d.ts @@ -8,6 +8,7 @@ import { MockInterceptor } from '../../types/mock-interceptor' // intercept expectAssignable(mockPool.intercept({ path: '', method: 'GET' })) expectAssignable(mockPool.intercept({ path: '', method: 'GET', body: '', headers: { 'User-Agent': '' } })) + // eslint-disable-next-line prefer-regex-literals expectAssignable(mockPool.intercept({ path: new RegExp(''), method: new RegExp(''), body: new RegExp(''), headers: { 'User-Agent': new RegExp('') } })) expectAssignable(mockPool.intercept({ path: (path) => { @@ -37,6 +38,4 @@ import { MockInterceptor } from '../../types/mock-interceptor' expectAssignable>(mockPool.close()) } -{ - expectAssignable(new MockPool('', {agent: new MockAgent({ connections: 1})})) -} +expectAssignable(new MockPool('', { agent: new MockAgent({ connections: 1 }) })) diff --git a/test/types/util.test-d.ts b/test/types/util.test-d.ts index 1dd59d84108..011f60030b7 100644 --- a/test/types/util.test-d.ts +++ b/test/types/util.test-d.ts @@ -1,25 +1,25 @@ -import { expectAssignable } from 'tsd'; -import { util } from '../../types/util'; +import { expectAssignable } from 'tsd' +import { util } from '../../types/util' expectAssignable>( util.parseHeaders(['content-type', 'text/plain']) -); +) expectAssignable>( util.parseHeaders([Buffer.from('content-type'), Buffer.from('text/plain')]) -); +) expectAssignable>( util.parseHeaders( [Buffer.from('content-type'), Buffer.from('text/plain')], {} ) -); +) expectAssignable>( util.parseHeaders([Buffer.from('content-type'), [Buffer.from('text/plain')]]) -); +) -expectAssignable(util.headerNameToString('content-type')); +expectAssignable(util.headerNameToString('content-type')) -expectAssignable(util.headerNameToString(Buffer.from('content-type'))); +expectAssignable(util.headerNameToString(Buffer.from('content-type'))) diff --git a/test/wpt/runner/util.mjs b/test/wpt/runner/util.mjs index 6bf8b777123..94c953381bf 100644 --- a/test/wpt/runner/util.mjs +++ b/test/wpt/runner/util.mjs @@ -101,7 +101,7 @@ export function handlePipes (code, url) { switch (sub) { // "The host name of the server excluding any subdomain part." - // eslint-disable-next-line no-fallthrough + case 'host': // "The domain name of a particular subdomain e.g. // {{domains[www]}} for the www subdomain." diff --git a/types/agent.d.ts b/types/agent.d.ts index 58081ce9372..74d9d5493a4 100644 --- a/types/agent.d.ts +++ b/types/agent.d.ts @@ -1,17 +1,17 @@ import { URL } from 'url' import Pool from './pool' -import Dispatcher from "./dispatcher"; +import Dispatcher from './dispatcher' export default Agent -declare class Agent extends Dispatcher{ - constructor(opts?: Agent.Options) +declare class Agent extends Dispatcher { + constructor (opts?: Agent.Options) /** `true` after `dispatcher.close()` has been called. */ - closed: boolean; + closed: boolean /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ - destroyed: boolean; + destroyed: boolean /** Dispatches a request. */ - dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean } declare namespace Agent { @@ -21,7 +21,7 @@ declare namespace Agent { /** Integer. Default: `0` */ maxRedirections?: number; - interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options['interceptors'] } export interface DispatchOptions extends Dispatcher.DispatchOptions { diff --git a/types/api.d.ts b/types/api.d.ts index 4fbebb6cd2e..e58d08f61cc 100644 --- a/types/api.d.ts +++ b/types/api.d.ts @@ -2,42 +2,42 @@ import { URL, UrlObject } from 'url' import { Duplex } from 'stream' import Dispatcher from './dispatcher' -export { - request, - stream, - pipeline, - connect, - upgrade, -} - /** Performs an HTTP request. */ -declare function request( +declare function request ( url: string | URL | UrlObject, options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path' | 'method'> & Partial>, -): Promise>; +): Promise> /** A faster version of `request`. */ -declare function stream( +declare function stream ( url: string | URL | UrlObject, options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, factory: Dispatcher.StreamFactory -): Promise>; +): Promise> /** For easy use with `stream.pipeline`. */ -declare function pipeline( +declare function pipeline ( url: string | URL | UrlObject, options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, handler: Dispatcher.PipelineHandler -): Duplex; +): Duplex /** Starts two-way communications with the requested resource. */ -declare function connect( +declare function connect ( url: string | URL | UrlObject, options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'> -): Promise>; +): Promise> /** Upgrade to a different protocol. */ -declare function upgrade( +declare function upgrade ( url: string | URL | UrlObject, options?: { dispatcher?: Dispatcher } & Omit -): Promise; +): Promise + +export { + request, + stream, + pipeline, + connect, + upgrade +} diff --git a/types/balanced-pool.d.ts b/types/balanced-pool.d.ts index 7f930f4108c..733239c0bf0 100644 --- a/types/balanced-pool.d.ts +++ b/types/balanced-pool.d.ts @@ -4,26 +4,26 @@ import { URL } from 'url' export default BalancedPool -type BalancedPoolConnectOptions = Omit; +type BalancedPoolConnectOptions = Omit declare class BalancedPool extends Dispatcher { - constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + constructor (url: string | string[] | URL | URL[], options?: Pool.Options) - addUpstream(upstream: string | URL): BalancedPool; - removeUpstream(upstream: string | URL): BalancedPool; - upstreams: Array; + addUpstream (upstream: string | URL): BalancedPool + removeUpstream (upstream: string | URL): BalancedPool + upstreams: Array /** `true` after `pool.close()` has been called. */ - closed: boolean; + closed: boolean /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ - destroyed: boolean; + destroyed: boolean // Override dispatcher APIs. - override connect( + override connect ( options: BalancedPoolConnectOptions - ): Promise; - override connect( + ): Promise + override connect ( options: BalancedPoolConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void - ): void; + ): void } diff --git a/types/client.d.ts b/types/client.d.ts index d0a5379f33c..f14e8092095 100644 --- a/types/client.d.ts +++ b/types/client.d.ts @@ -1,30 +1,29 @@ import { URL } from 'url' -import { TlsOptions } from 'tls' import Dispatcher from './dispatcher' -import buildConnector from "./connector"; +import buildConnector from './connector' -type ClientConnectOptions = Omit; +type ClientConnectOptions = Omit /** * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. */ export class Client extends Dispatcher { - constructor(url: string | URL, options?: Client.Options); + constructor (url: string | URL, options?: Client.Options) /** Property to get and set the pipelining factor. */ - pipelining: number; + pipelining: number /** `true` after `client.close()` has been called. */ - closed: boolean; + closed: boolean /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ - destroyed: boolean; + destroyed: boolean // Override dispatcher APIs. - override connect( + override connect ( options: ClientConnectOptions - ): Promise; - override connect( + ): Promise + override connect ( options: ClientConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void - ): void; + ): void } export declare namespace Client { @@ -105,4 +104,4 @@ export declare namespace Client { } } -export default Client; +export default Client diff --git a/types/diagnostics-channel.d.ts b/types/diagnostics-channel.d.ts index a037d1e0b2c..0c8477e16a8 100644 --- a/types/diagnostics-channel.d.ts +++ b/types/diagnostics-channel.d.ts @@ -1,7 +1,7 @@ -import { Socket } from "net"; -import { URL } from "url"; -import Connector from "./connector"; -import Dispatcher from "./dispatcher"; +import { Socket } from 'net' +import { URL } from 'url' +import buildConnector from './connector' +import Dispatcher from './dispatcher' declare namespace DiagnosticsChannel { interface Request { @@ -16,15 +16,15 @@ declare namespace DiagnosticsChannel { statusText: string; headers: Array; } - type Error = unknown; + type Error = unknown interface ConnectParams { - host: URL["host"]; - hostname: URL["hostname"]; - protocol: URL["protocol"]; - port: URL["port"]; + host: URL['host']; + hostname: URL['hostname']; + protocol: URL['protocol']; + port: URL['port']; servername: string | null; } - type Connector = Connector.connector; + type Connector = buildConnector.connector export interface RequestCreateMessage { request: Request; } diff --git a/types/dispatcher.d.ts b/types/dispatcher.d.ts index a2cb6ba72d8..7a9810a2c47 100644 --- a/types/dispatcher.d.ts +++ b/types/dispatcher.d.ts @@ -8,97 +8,94 @@ import { FormData } from './formdata' import Errors from './errors' import { Autocomplete } from './utility' -type AbortSignal = unknown; +type AbortSignal = unknown export default Dispatcher /** Dispatcher is the core API used to dispatch requests. */ declare class Dispatcher extends EventEmitter { /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ - dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + dispatch (options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean /** Starts two-way communications with the requested resource. */ - connect(options: Dispatcher.ConnectOptions): Promise>; - connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + connect(options: Dispatcher.ConnectOptions): Promise> + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void /** Compose a chain of dispatchers */ - compose(dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher; - compose(...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher; + compose (dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + compose (...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher /** Performs an HTTP request. */ - request(options: Dispatcher.RequestOptions): Promise>; - request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + request(options: Dispatcher.RequestOptions): Promise> + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void /** For easy use with `stream.pipeline`. */ - pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex /** A faster version of `Dispatcher.request`. */ - stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise>; - stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise> + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void /** Upgrade to a different protocol. */ - upgrade(options: Dispatcher.UpgradeOptions): Promise; - upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + upgrade (options: Dispatcher.UpgradeOptions): Promise + upgrade (options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ - close(): Promise; - close(callback: () => void): void; + close (): Promise + close (callback: () => void): void /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ - destroy(): Promise; - destroy(err: Error | null): Promise; - destroy(callback: () => void): void; - destroy(err: Error | null, callback: () => void): void; - - on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - on(eventName: 'drain', callback: (origin: URL) => void): this; - - - once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - once(eventName: 'drain', callback: (origin: URL) => void): this; - - - off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - off(eventName: 'drain', callback: (origin: URL) => void): this; - - - addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - addListener(eventName: 'drain', callback: (origin: URL) => void): this; - - removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - removeListener(eventName: 'drain', callback: (origin: URL) => void): this; - - prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - prependListener(eventName: 'drain', callback: (origin: URL) => void): this; - - prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; - prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; - prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; - - listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] - listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; - listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; - listeners(eventName: 'drain'): ((origin: URL) => void)[]; - - rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] - rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; - rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; - rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; - - emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; - emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; - emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; - emit(eventName: 'drain', origin: URL): boolean; + destroy (): Promise + destroy (err: Error | null): Promise + destroy (callback: () => void): void + destroy (err: Error | null, callback: () => void): void + + on (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + on (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'drain', callback: (origin: URL) => void): this + + once (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + once (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'drain', callback: (origin: URL) => void): this + + off (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + off (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'drain', callback: (origin: URL) => void): this + + addListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + addListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'drain', callback: (origin: URL) => void): this + + removeListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + removeListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependOnceListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependOnceListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'drain', callback: (origin: URL) => void): this + + listeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'drain'): ((origin: URL) => void)[] + + rawListeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'drain'): ((origin: URL) => void)[] + + emit (eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean + emit (eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'drain', origin: URL): boolean } declare namespace Dispatcher { export interface ComposedDispatcher extends Dispatcher {} - export type DispatcherComposeInterceptor = (dispatch: Dispatcher['dispatch']) => Dispatcher['dispatch']; + export type DispatcherComposeInterceptor = (dispatch: Dispatcher['dispatch']) => Dispatcher['dispatch'] export interface DispatchOptions { origin?: string | URL; path: string; @@ -123,7 +120,7 @@ declare namespace Dispatcher { reset?: boolean; /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ throwOnError?: boolean; - /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server */ expectContinue?: boolean; } export interface ConnectOptions { @@ -215,7 +212,7 @@ declare namespace Dispatcher { opaque: TOpaque; context: object; } - export type StreamFactory = (data: StreamFactoryData) => Writable; + export type StreamFactory = (data: StreamFactoryData) => Writable export interface DispatchHandlers { /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ onConnect?(abort: (err?: Error) => void): void; @@ -234,8 +231,8 @@ declare namespace Dispatcher { /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ onBodySent?(chunkSize: number, totalBytesSent: number): void; } - export type PipelineHandler = (data: PipelineHandlerData) => Readable; - export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'>; + export type PipelineHandler = (data: PipelineHandlerData) => Readable + export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'> /** * @link https://fetch.spec.whatwg.org/#body-mixin diff --git a/types/env-http-proxy-agent.d.ts b/types/env-http-proxy-agent.d.ts index d6509dc673b..f5b1dc43060 100644 --- a/types/env-http-proxy-agent.d.ts +++ b/types/env-http-proxy-agent.d.ts @@ -4,9 +4,9 @@ import Dispatcher from './dispatcher' export default EnvHttpProxyAgent declare class EnvHttpProxyAgent extends Dispatcher { - constructor(opts?: EnvHttpProxyAgent.Options) + constructor (opts?: EnvHttpProxyAgent.Options) - dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean } declare namespace EnvHttpProxyAgent { diff --git a/types/errors.d.ts b/types/errors.d.ts index a23ed5558b3..fdf806e90a1 100644 --- a/types/errors.d.ts +++ b/types/errors.d.ts @@ -1,24 +1,24 @@ -import { IncomingHttpHeaders } from "./header"; +import { IncomingHttpHeaders } from './header' import Client from './client' export default Errors declare namespace Errors { export class UndiciError extends Error { - name: string; - code: string; + name: string + code: string } /** Connect timeout error. */ export class ConnectTimeoutError extends UndiciError { - name: 'ConnectTimeoutError'; - code: 'UND_ERR_CONNECT_TIMEOUT'; + name: 'ConnectTimeoutError' + code: 'UND_ERR_CONNECT_TIMEOUT' } /** A header exceeds the `headersTimeout` option. */ export class HeadersTimeoutError extends UndiciError { - name: 'HeadersTimeoutError'; - code: 'UND_ERR_HEADERS_TIMEOUT'; + name: 'HeadersTimeoutError' + code: 'UND_ERR_HEADERS_TIMEOUT' } /** Headers overflow error. */ @@ -29,8 +29,8 @@ declare namespace Errors { /** A body exceeds the `bodyTimeout` option. */ export class BodyTimeoutError extends UndiciError { - name: 'BodyTimeoutError'; - code: 'UND_ERR_BODY_TIMEOUT'; + name: 'BodyTimeoutError' + code: 'UND_ERR_BODY_TIMEOUT' } export class ResponseStatusCodeError extends UndiciError { @@ -39,91 +39,91 @@ declare namespace Errors { statusCode?: number, headers?: IncomingHttpHeaders | string[] | null, body?: null | Record | string - ); - name: 'ResponseStatusCodeError'; - code: 'UND_ERR_RESPONSE_STATUS_CODE'; + ) + name: 'ResponseStatusCodeError' + code: 'UND_ERR_RESPONSE_STATUS_CODE' body: null | Record | string status: number statusCode: number - headers: IncomingHttpHeaders | string[] | null; + headers: IncomingHttpHeaders | string[] | null } /** Passed an invalid argument. */ export class InvalidArgumentError extends UndiciError { - name: 'InvalidArgumentError'; - code: 'UND_ERR_INVALID_ARG'; + name: 'InvalidArgumentError' + code: 'UND_ERR_INVALID_ARG' } /** Returned an invalid value. */ export class InvalidReturnValueError extends UndiciError { - name: 'InvalidReturnValueError'; - code: 'UND_ERR_INVALID_RETURN_VALUE'; + name: 'InvalidReturnValueError' + code: 'UND_ERR_INVALID_RETURN_VALUE' } /** The request has been aborted by the user. */ export class RequestAbortedError extends UndiciError { - name: 'AbortError'; - code: 'UND_ERR_ABORTED'; + name: 'AbortError' + code: 'UND_ERR_ABORTED' } /** Expected error with reason. */ export class InformationalError extends UndiciError { - name: 'InformationalError'; - code: 'UND_ERR_INFO'; + name: 'InformationalError' + code: 'UND_ERR_INFO' } /** Request body length does not match content-length header. */ export class RequestContentLengthMismatchError extends UndiciError { - name: 'RequestContentLengthMismatchError'; - code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + name: 'RequestContentLengthMismatchError' + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' } /** Response body length does not match content-length header. */ export class ResponseContentLengthMismatchError extends UndiciError { - name: 'ResponseContentLengthMismatchError'; - code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + name: 'ResponseContentLengthMismatchError' + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' } /** Trying to use a destroyed client. */ export class ClientDestroyedError extends UndiciError { - name: 'ClientDestroyedError'; - code: 'UND_ERR_DESTROYED'; + name: 'ClientDestroyedError' + code: 'UND_ERR_DESTROYED' } /** Trying to use a closed client. */ export class ClientClosedError extends UndiciError { - name: 'ClientClosedError'; - code: 'UND_ERR_CLOSED'; + name: 'ClientClosedError' + code: 'UND_ERR_CLOSED' } /** There is an error with the socket. */ export class SocketError extends UndiciError { - name: 'SocketError'; - code: 'UND_ERR_SOCKET'; + name: 'SocketError' + code: 'UND_ERR_SOCKET' socket: Client.SocketInfo | null } /** Encountered unsupported functionality. */ export class NotSupportedError extends UndiciError { - name: 'NotSupportedError'; - code: 'UND_ERR_NOT_SUPPORTED'; + name: 'NotSupportedError' + code: 'UND_ERR_NOT_SUPPORTED' } /** No upstream has been added to the BalancedPool. */ export class BalancedPoolMissingUpstreamError extends UndiciError { - name: 'MissingUpstreamError'; - code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + name: 'MissingUpstreamError' + code: 'UND_ERR_BPL_MISSING_UPSTREAM' } export class HTTPParserError extends UndiciError { - name: 'HTTPParserError'; - code: string; + name: 'HTTPParserError' + code: string } /** The response exceed the length allowed. */ export class ResponseExceededMaxSizeError extends UndiciError { - name: 'ResponseExceededMaxSizeError'; - code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + name: 'ResponseExceededMaxSizeError' + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE' } export class RequestRetryError extends UndiciError { @@ -132,14 +132,15 @@ declare namespace Errors { statusCode: number, headers?: IncomingHttpHeaders | string[] | null, body?: null | Record | string - ); - name: 'RequestRetryError'; - code: 'UND_ERR_REQ_RETRY'; - statusCode: number; + ) + name: 'RequestRetryError' + code: 'UND_ERR_REQ_RETRY' + statusCode: number data: { count: number; - }; - headers: Record; + } + + headers: Record } export class SecureProxyConnectionError extends UndiciError { @@ -147,8 +148,8 @@ declare namespace Errors { cause?: Error, message?: string, options?: Record - ); - name: 'SecureProxyConnectionError'; - code: 'UND_ERR_PRX_TLS'; + ) + name: 'SecureProxyConnectionError' + code: 'UND_ERR_PRX_TLS' } } diff --git a/types/fetch.d.ts b/types/fetch.d.ts index 20c1839acd2..7c2b1c98ccd 100644 --- a/types/fetch.d.ts +++ b/types/fetch.d.ts @@ -36,17 +36,17 @@ export class BodyMixin { /** * @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments. * It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows: - * + * * @example * ```js * import { Busboy } from '@fastify/busboy' * import { Readable } from 'node:stream' - * + * * const response = await fetch('...') * const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } }) - * + * * // handle events emitted from `busboy` - * + * * Readable.fromWeb(response.body).pipe(busboy) * ``` */ @@ -144,7 +144,7 @@ export type ReferrerPolicy = | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' - | 'unsafe-url'; + | 'unsafe-url' export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' @@ -204,6 +204,6 @@ export declare class Response extends BodyMixin { readonly clone: () => Response static error (): Response - static json(data: any, init?: ResponseInit): Response + static json (data: any, init?: ResponseInit): Response static redirect (url: string | URL, status: ResponseRedirectStatus): Response } diff --git a/types/formdata.d.ts b/types/formdata.d.ts index 50e5d37c724..030f5485950 100644 --- a/types/formdata.d.ts +++ b/types/formdata.d.ts @@ -24,7 +24,7 @@ export declare class FormData { or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. */ - append(name: string, value: unknown, fileName?: string): void + append (name: string, value: unknown, fileName?: string): void /** * Set a new value for an existing key inside FormData, @@ -36,7 +36,7 @@ export declare class FormData { * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. * */ - set(name: string, value: unknown, fileName?: string): void + set (name: string, value: unknown, fileName?: string): void /** * Returns the first value associated with a given key from within a `FormData` object. @@ -46,7 +46,7 @@ export declare class FormData { * * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. */ - get(name: string): FormDataEntryValue | null + get (name: string): FormDataEntryValue | null /** * Returns all the values associated with a given key from within a `FormData` object. @@ -55,7 +55,7 @@ export declare class FormData { * * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. */ - getAll(name: string): FormDataEntryValue[] + getAll (name: string): FormDataEntryValue[] /** * Returns a boolean stating whether a `FormData` object contains a certain key. @@ -64,14 +64,14 @@ export declare class FormData { * * @return A boolean value. */ - has(name: string): boolean + has (name: string): boolean /** * Deletes a key and its value(s) from a `FormData` object. * * @param name The name of the key you want to delete. */ - delete(name: string): void + delete (name: string): void /** * Executes given callback function for each field of the FormData instance diff --git a/types/global-dispatcher.d.ts b/types/global-dispatcher.d.ts index 728f95ce23c..2760e136de4 100644 --- a/types/global-dispatcher.d.ts +++ b/types/global-dispatcher.d.ts @@ -1,9 +1,9 @@ -import Dispatcher from "./dispatcher"; +import Dispatcher from './dispatcher' + +declare function setGlobalDispatcher (dispatcher: DispatcherImplementation): void +declare function getGlobalDispatcher (): Dispatcher export { getGlobalDispatcher, setGlobalDispatcher } - -declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; -declare function getGlobalDispatcher(): Dispatcher; diff --git a/types/global-origin.d.ts b/types/global-origin.d.ts index 322542d6675..265769b7b4e 100644 --- a/types/global-origin.d.ts +++ b/types/global-origin.d.ts @@ -1,7 +1,7 @@ +declare function setGlobalOrigin (origin: string | URL | undefined): void +declare function getGlobalOrigin (): URL | undefined + export { - setGlobalOrigin, - getGlobalOrigin + setGlobalOrigin, + getGlobalOrigin } - -declare function setGlobalOrigin(origin: string | URL | undefined): void; -declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/types/handlers.d.ts b/types/handlers.d.ts index afcda9a3e1d..e95451540c9 100644 --- a/types/handlers.d.ts +++ b/types/handlers.d.ts @@ -1,15 +1,15 @@ -import Dispatcher from "./dispatcher"; +import Dispatcher from './dispatcher' export declare class RedirectHandler implements Dispatcher.DispatchHandlers { - constructor( + constructor ( dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers, redirectionLimitReached: boolean - ); + ) } export declare class DecoratorHandler implements Dispatcher.DispatchHandlers { - constructor(handler: Dispatcher.DispatchHandlers); + constructor (handler: Dispatcher.DispatchHandlers) } diff --git a/types/header.d.ts b/types/header.d.ts index d514ede077e..efd7b1dd0bb 100644 --- a/types/header.d.ts +++ b/types/header.d.ts @@ -1,9 +1,9 @@ -import { Autocomplete } from "./utility"; +import { Autocomplete } from './utility' /** * The header type declaration of `undici`. */ -export type IncomingHttpHeaders = Record; +export type IncomingHttpHeaders = Record type HeaderNames = Autocomplete< | 'Accept' diff --git a/types/index.d.ts b/types/index.d.ts index 5b540211df7..45276234925 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,22 +1,22 @@ -import Dispatcher from'./dispatcher' +import Dispatcher from './dispatcher' import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' import { setGlobalOrigin, getGlobalOrigin } from './global-origin' -import Pool from'./pool' +import Pool from './pool' import { RedirectHandler, DecoratorHandler } from './handlers' import BalancedPool from './balanced-pool' -import Client from'./client' -import buildConnector from'./connector' -import errors from'./errors' -import Agent from'./agent' -import MockClient from'./mock-client' -import MockPool from'./mock-pool' -import MockAgent from'./mock-agent' -import mockErrors from'./mock-errors' -import ProxyAgent from'./proxy-agent' +import Client from './client' +import buildConnector from './connector' +import errors from './errors' +import Agent from './agent' +import MockClient from './mock-client' +import MockPool from './mock-pool' +import MockAgent from './mock-agent' +import mockErrors from './mock-errors' +import ProxyAgent from './proxy-agent' import EnvHttpProxyAgent from './env-http-proxy-agent' -import RetryHandler from'./retry-handler' -import RetryAgent from'./retry-agent' +import RetryHandler from './retry-handler' +import RetryAgent from './retry-agent' import { request, pipeline, stream, connect, upgrade } from './api' import interceptors from './interceptors' @@ -35,33 +35,33 @@ export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, export default Undici declare namespace Undici { - var Dispatcher: typeof import('./dispatcher').default - var Pool: typeof import('./pool').default; - var RedirectHandler: typeof import ('./handlers').RedirectHandler - var DecoratorHandler: typeof import ('./handlers').DecoratorHandler - var RetryHandler: typeof import ('./retry-handler').default - var createRedirectInterceptor: typeof import ('./interceptors').default.createRedirectInterceptor - var BalancedPool: typeof import('./balanced-pool').default; - var Client: typeof import('./client').default; - var buildConnector: typeof import('./connector').default; - var errors: typeof import('./errors').default; - var Agent: typeof import('./agent').default; - var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; - var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; - var request: typeof import('./api').request; - var stream: typeof import('./api').stream; - var pipeline: typeof import('./api').pipeline; - var connect: typeof import('./api').connect; - var upgrade: typeof import('./api').upgrade; - var MockClient: typeof import('./mock-client').default; - var MockPool: typeof import('./mock-pool').default; - var MockAgent: typeof import('./mock-agent').default; - var mockErrors: typeof import('./mock-errors').default; - var fetch: typeof import('./fetch').fetch; - var Headers: typeof import('./fetch').Headers; - var Response: typeof import('./fetch').Response; - var Request: typeof import('./fetch').Request; - var FormData: typeof import('./formdata').FormData; - var caches: typeof import('./cache').caches; - var interceptors: typeof import('./interceptors').default; + const Dispatcher: typeof import('./dispatcher').default + const Pool: typeof import('./pool').default + const RedirectHandler: typeof import ('./handlers').RedirectHandler + const DecoratorHandler: typeof import ('./handlers').DecoratorHandler + const RetryHandler: typeof import ('./retry-handler').default + const createRedirectInterceptor: typeof import ('./interceptors').default.createRedirectInterceptor + const BalancedPool: typeof import('./balanced-pool').default + const Client: typeof import('./client').default + const buildConnector: typeof import('./connector').default + const errors: typeof import('./errors').default + const Agent: typeof import('./agent').default + const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher + const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher + const request: typeof import('./api').request + const stream: typeof import('./api').stream + const pipeline: typeof import('./api').pipeline + const connect: typeof import('./api').connect + const upgrade: typeof import('./api').upgrade + const MockClient: typeof import('./mock-client').default + const MockPool: typeof import('./mock-pool').default + const MockAgent: typeof import('./mock-agent').default + const mockErrors: typeof import('./mock-errors').default + const fetch: typeof import('./fetch').fetch + const Headers: typeof import('./fetch').Headers + const Response: typeof import('./fetch').Response + const Request: typeof import('./fetch').Request + const FormData: typeof import('./formdata').FormData + const caches: typeof import('./cache').caches + const interceptors: typeof import('./interceptors').default } diff --git a/types/interceptors.d.ts b/types/interceptors.d.ts index 24166b61f4f..53835e01299 100644 --- a/types/interceptors.d.ts +++ b/types/interceptors.d.ts @@ -1,7 +1,7 @@ -import Dispatcher from "./dispatcher"; -import RetryHandler from "./retry-handler"; +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' -export default Interceptors; +export default Interceptors declare namespace Interceptors { export type DumpInterceptorOpts = { maxSize?: number } @@ -9,9 +9,9 @@ declare namespace Interceptors { export type RedirectInterceptorOpts = { maxRedirections?: number } export type ResponseErrorInterceptorOpts = { throwOnError: boolean } - export function createRedirectInterceptor(opts: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor - export function dump(opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor - export function retry(opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor - export function redirect(opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor - export function responseError(opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function retry (opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function redirect (opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function responseError (opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor } diff --git a/types/mock-agent.d.ts b/types/mock-agent.d.ts index 98cd645b29b..17c09386f3f 100644 --- a/types/mock-agent.d.ts +++ b/types/mock-agent.d.ts @@ -1,7 +1,7 @@ import Agent from './agent' import Dispatcher from './dispatcher' import { Interceptable, MockInterceptor } from './mock-interceptor' -import MockDispatch = MockInterceptor.MockDispatch; +import MockDispatch = MockInterceptor.MockDispatch export default MockAgent @@ -11,30 +11,30 @@ interface PendingInterceptor extends MockDispatch { /** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ declare class MockAgent extends Dispatcher { - constructor(options?: MockAgent.Options) + constructor (options?: TMockAgentOptions) /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ - get(origin: string): TInterceptable; - get(origin: RegExp): TInterceptable; - get(origin: ((origin: string) => boolean)): TInterceptable; + get(origin: string): TInterceptable + get(origin: RegExp): TInterceptable + get(origin: ((origin: string) => boolean)): TInterceptable /** Dispatches a mocked request. */ - dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ - close(): Promise; + close (): Promise /** Disables mocking in MockAgent. */ - deactivate(): void; + deactivate (): void /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ - activate(): void; + activate (): void /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ - enableNetConnect(): void; - enableNetConnect(host: string): void; - enableNetConnect(host: RegExp): void; - enableNetConnect(host: ((host: string) => boolean)): void; + enableNetConnect (): void + enableNetConnect (host: string): void + enableNetConnect (host: RegExp): void + enableNetConnect (host: ((host: string) => boolean)): void /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ - disableNetConnect(): void; - pendingInterceptors(): PendingInterceptor[]; - assertNoPendingInterceptors(options?: { + disableNetConnect (): void + pendingInterceptors (): PendingInterceptor[] + assertNoPendingInterceptors (options?: { pendingInterceptorsFormatter?: PendingInterceptorsFormatter; - }): void; + }): void } interface PendingInterceptorsFormatter { diff --git a/types/mock-client.d.ts b/types/mock-client.d.ts index 51d008cc11c..704e48a6eec 100644 --- a/types/mock-client.d.ts +++ b/types/mock-client.d.ts @@ -7,13 +7,13 @@ export default MockClient /** MockClient extends the Client API and allows one to mock requests. */ declare class MockClient extends Client implements Interceptable { - constructor(origin: string, options: MockClient.Options); + constructor (origin: string, options: MockClient.Options) /** Intercepts any matching requests that use the same origin as this mock client. */ - intercept(options: MockInterceptor.Options): MockInterceptor; + intercept (options: MockInterceptor.Options): MockInterceptor /** Dispatches a mocked request. */ - dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean /** Closes the mock client and gracefully waits for enqueued requests to complete. */ - close(): Promise; + close (): Promise } declare namespace MockClient { diff --git a/types/mock-errors.d.ts b/types/mock-errors.d.ts index 3d9e727d70a..eefeecd62ee 100644 --- a/types/mock-errors.d.ts +++ b/types/mock-errors.d.ts @@ -5,8 +5,8 @@ export default MockErrors declare namespace MockErrors { /** The request does not match any registered mock dispatches. */ export class MockNotMatchedError extends Errors.UndiciError { - constructor(message?: string); - name: 'MockNotMatchedError'; - code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + constructor (message?: string) + name: 'MockNotMatchedError' + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED' } } diff --git a/types/mock-interceptor.d.ts b/types/mock-interceptor.d.ts index 33f3f14d1bf..418db413e5d 100644 --- a/types/mock-interceptor.d.ts +++ b/types/mock-interceptor.d.ts @@ -1,42 +1,36 @@ import { IncomingHttpHeaders } from './header' -import Dispatcher from './dispatcher'; +import Dispatcher from './dispatcher' import { BodyInit, Headers } from './fetch' -export { - Interceptable, - MockInterceptor, - MockScope -} - /** The scope associated with a mock dispatch. */ declare class MockScope { - constructor(mockDispatch: MockInterceptor.MockDispatch); + constructor (mockDispatch: MockInterceptor.MockDispatch) /** Delay a reply by a set amount of time in ms. */ - delay(waitInMs: number): MockScope; + delay (waitInMs: number): MockScope /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ - persist(): MockScope; + persist (): MockScope /** Define a reply for a set amount of matching requests. */ - times(repeatTimes: number): MockScope; + times (repeatTimes: number): MockScope } /** The interceptor for a Mock. */ declare class MockInterceptor { - constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + constructor (options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]) /** Mock an undici request with the defined reply. */ - reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope reply( statusCode: number, data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, responseOptions?: MockInterceptor.MockResponseOptions - ): MockScope; + ): MockScope /** Mock an undici request by throwing the defined reply error. */ - replyWithError(error: TError): MockScope; + replyWithError(error: TError): MockScope /** Set default reply headers on the interceptor for subsequent mocked replies. */ - defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + defaultReplyHeaders (headers: IncomingHttpHeaders): MockInterceptor /** Set default reply trailers on the interceptor for subsequent mocked replies. */ - defaultReplyTrailers(trailers: Record): MockInterceptor; + defaultReplyTrailers (trailers: Record): MockInterceptor /** Set automatically calculated content-length header on subsequent mocked replies. */ - replyContentLength(): MockInterceptor; + replyContentLength (): MockInterceptor } declare namespace MockInterceptor { @@ -80,7 +74,7 @@ declare namespace MockInterceptor { export type MockResponseDataHandler = ( opts: MockResponseCallbackOptions - ) => TData | Buffer | string; + ) => TData | Buffer | string export type MockReplyOptionsCallback = ( opts: MockResponseCallbackOptions @@ -91,3 +85,9 @@ interface Interceptable extends Dispatcher { /** Intercepts any matching requests that use the same origin as this mock client. */ intercept(options: MockInterceptor.Options): MockInterceptor; } + +export { + Interceptable, + MockInterceptor, + MockScope +} diff --git a/types/mock-pool.d.ts b/types/mock-pool.d.ts index 39e709aaf69..7ef52767366 100644 --- a/types/mock-pool.d.ts +++ b/types/mock-pool.d.ts @@ -7,13 +7,13 @@ export default MockPool /** MockPool extends the Pool API and allows one to mock requests. */ declare class MockPool extends Pool implements Interceptable { - constructor(origin: string, options: MockPool.Options); + constructor (origin: string, options: MockPool.Options) /** Intercepts any matching requests that use the same origin as this mock pool. */ - intercept(options: MockInterceptor.Options): MockInterceptor; + intercept (options: MockInterceptor.Options): MockInterceptor /** Dispatches a mocked request. */ - dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ - close(): Promise; + close (): Promise } declare namespace MockPool { diff --git a/types/patch.d.ts b/types/patch.d.ts index 3871acfebc6..e48700f4c6f 100644 --- a/types/patch.d.ts +++ b/types/patch.d.ts @@ -3,46 +3,46 @@ // See https://github.com/nodejs/undici/issues/1740 export type DOMException = typeof globalThis extends { DOMException: infer T } - ? T - : any + ? T + : any export type EventTarget = typeof globalThis extends { EventTarget: infer T } ? T : { - addEventListener( - type: string, - listener: any, - options?: any, - ): void - dispatchEvent(event: Event): boolean - removeEventListener( - type: string, - listener: any, - options?: any | boolean, - ): void - } + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } export type Event = typeof globalThis extends { Event: infer T } ? T : { - readonly bubbles: boolean - cancelBubble: () => void - readonly cancelable: boolean - readonly composed: boolean - composedPath(): [EventTarget?] - readonly currentTarget: EventTarget | null - readonly defaultPrevented: boolean - readonly eventPhase: 0 | 2 - readonly isTrusted: boolean - preventDefault(): void - returnValue: boolean - readonly srcElement: EventTarget | null - stopImmediatePropagation(): void - stopPropagation(): void - readonly target: EventTarget | null - readonly timeStamp: number - readonly type: string - } + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } export interface EventInit { bubbles?: boolean diff --git a/types/pool-stats.d.ts b/types/pool-stats.d.ts index 8b6d2bff4ad..f76a5f61ddd 100644 --- a/types/pool-stats.d.ts +++ b/types/pool-stats.d.ts @@ -1,19 +1,19 @@ -import Pool from "./pool" +import Pool from './pool' export default PoolStats declare class PoolStats { - constructor(pool: Pool); + constructor (pool: Pool) /** Number of open socket connections in this pool. */ - connected: number; + connected: number /** Number of open socket connections in this pool that do not have an active request. */ - free: number; + free: number /** Number of pending requests across all clients in this pool. */ - pending: number; + pending: number /** Number of queued requests across all clients in this pool. */ - queued: number; + queued: number /** Number of currently active requests across all clients in this pool. */ - running: number; + running: number /** Number of active, pending, or queued requests across all clients in this pool. */ - size: number; + size: number } diff --git a/types/pool.d.ts b/types/pool.d.ts index bad5ba0308e..4814606a702 100644 --- a/types/pool.d.ts +++ b/types/pool.d.ts @@ -1,39 +1,39 @@ import Client from './client' import TPoolStats from './pool-stats' import { URL } from 'url' -import Dispatcher from "./dispatcher"; +import Dispatcher from './dispatcher' export default Pool -type PoolConnectOptions = Omit; +type PoolConnectOptions = Omit declare class Pool extends Dispatcher { - constructor(url: string | URL, options?: Pool.Options) + constructor (url: string | URL, options?: Pool.Options) /** `true` after `pool.close()` has been called. */ - closed: boolean; + closed: boolean /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ - destroyed: boolean; + destroyed: boolean /** Aggregate stats for a Pool. */ - readonly stats: TPoolStats; + readonly stats: TPoolStats // Override dispatcher APIs. - override connect( + override connect ( options: PoolConnectOptions - ): Promise; - override connect( + ): Promise + override connect ( options: PoolConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void - ): void; + ): void } declare namespace Pool { - export type PoolStats = TPoolStats; + export type PoolStats = TPoolStats export interface Options extends Client.Options { /** Default: `(origin, opts) => new Client(origin, opts)`. */ factory?(origin: URL, opts: object): Dispatcher; /** The max number of clients to create. `null` if no limit. Default `null`. */ connections?: number | null; - interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options['interceptors'] } } diff --git a/types/proxy-agent.d.ts b/types/proxy-agent.d.ts index 32e3acbdaad..5350dbc2e60 100644 --- a/types/proxy-agent.d.ts +++ b/types/proxy-agent.d.ts @@ -1,15 +1,15 @@ import Agent from './agent' -import buildConnector from './connector'; +import buildConnector from './connector' import Dispatcher from './dispatcher' import { IncomingHttpHeaders } from './header' export default ProxyAgent declare class ProxyAgent extends Dispatcher { - constructor(options: ProxyAgent.Options | string) + constructor (options: ProxyAgent.Options | string) - dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; - close(): Promise; + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean + close (): Promise } declare namespace ProxyAgent { diff --git a/types/readable.d.ts b/types/readable.d.ts index c4f052af05e..703f6fa806f 100644 --- a/types/readable.d.ts +++ b/types/readable.d.ts @@ -1,10 +1,10 @@ -import { Readable } from "stream"; +import { Readable } from 'stream' import { Blob } from 'buffer' export default BodyReadable declare class BodyReadable extends Readable { - constructor( + constructor ( resume?: (this: Readable, size: number) => void | null, abort?: () => void | null, contentType?: string @@ -13,33 +13,33 @@ declare class BodyReadable extends Readable { /** Consumes and returns the body as a string * https://fetch.spec.whatwg.org/#dom-body-text */ - text(): Promise + text (): Promise /** Consumes and returns the body as a JavaScript Object * https://fetch.spec.whatwg.org/#dom-body-json */ - json(): Promise + json (): Promise /** Consumes and returns the body as a Blob * https://fetch.spec.whatwg.org/#dom-body-blob */ - blob(): Promise + blob (): Promise /** Consumes and returns the body as an Uint8Array * https://fetch.spec.whatwg.org/#dom-body-bytes */ - bytes(): Promise + bytes (): Promise /** Consumes and returns the body as an ArrayBuffer * https://fetch.spec.whatwg.org/#dom-body-arraybuffer */ - arrayBuffer(): Promise + arrayBuffer (): Promise /** Not implemented * * https://fetch.spec.whatwg.org/#dom-body-formdata */ - formData(): Promise + formData (): Promise /** Returns true if the body is not null and the body has been consumed * @@ -49,7 +49,7 @@ declare class BodyReadable extends Readable { */ readonly bodyUsed: boolean - /** + /** * If body is null, it should return null as the body * * If body is not null, should return the body as a ReadableStream @@ -61,5 +61,5 @@ declare class BodyReadable extends Readable { /** Dumps the response body by reading `limit` number of bytes. * @param opts.limit Number of bytes to read (optional) - Default: 262144 */ - dump(opts?: { limit: number }): Promise + dump (opts?: { limit: number }): Promise } diff --git a/types/retry-agent.d.ts b/types/retry-agent.d.ts index 963cea99e42..82268c37388 100644 --- a/types/retry-agent.d.ts +++ b/types/retry-agent.d.ts @@ -4,5 +4,5 @@ import RetryHandler from './retry-handler' export default RetryAgent declare class RetryAgent extends Dispatcher { - constructor(dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) + constructor (dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) } diff --git a/types/retry-handler.d.ts b/types/retry-handler.d.ts index e44b207c221..eedd353bfce 100644 --- a/types/retry-handler.d.ts +++ b/types/retry-handler.d.ts @@ -1,18 +1,18 @@ -import Dispatcher from "./dispatcher"; +import Dispatcher from './dispatcher' -export default RetryHandler; +export default RetryHandler declare class RetryHandler implements Dispatcher.DispatchHandlers { - constructor( + constructor ( options: Dispatcher.DispatchOptions & { retryOptions?: RetryHandler.RetryOptions; }, retryHandlers: RetryHandler.RetryHandlers - ); + ) } declare namespace RetryHandler { - export type RetryState = { counter: number; }; + export type RetryState = { counter: number; } export type RetryContext = { state: RetryState; @@ -21,7 +21,7 @@ declare namespace RetryHandler { }; } - export type OnRetryCallback = (result?: Error | null) => void; + export type OnRetryCallback = (result?: Error | null) => void export type RetryCallback = ( err: Error, @@ -32,7 +32,7 @@ declare namespace RetryHandler { }; }, callback: OnRetryCallback - ) => number | null; + ) => number | null export interface RetryOptions { /** @@ -110,7 +110,7 @@ declare namespace RetryHandler { } export interface RetryHandlers { - dispatch: Dispatcher["dispatch"]; + dispatch: Dispatcher['dispatch']; handler: Dispatcher.DispatchHandlers; } } diff --git a/types/util.d.ts b/types/util.d.ts index 77cf1473a24..8fc50cc4243 100644 --- a/types/util.d.ts +++ b/types/util.d.ts @@ -3,7 +3,7 @@ export namespace util { * Retrieves a header name and returns its lowercase value. * @param value Header name */ - export function headerNameToString(value: string | Buffer): string; + export function headerNameToString (value: string | Buffer): string /** * Receives a header object and returns the parsed value. @@ -11,8 +11,8 @@ export namespace util { * @param obj Object to specify a proxy object. Used to assign parsed values. * @returns If `obj` is specified, it is equivalent to `obj`. */ - export function parseHeaders( + export function parseHeaders ( headers: (Buffer | string | (Buffer | string)[])[], obj?: Record - ): Record; + ): Record } diff --git a/types/utility.d.ts b/types/utility.d.ts index 9c2b5628e3a..bfb3ca7700c 100644 --- a/types/utility.d.ts +++ b/types/utility.d.ts @@ -1,7 +1,7 @@ type AutocompletePrimitiveBaseType = T extends string ? string : - T extends number ? number : - T extends boolean ? boolean : - never; + T extends number ? number : + T extends boolean ? boolean : + never -export type Autocomplete = T | (AutocompletePrimitiveBaseType & Record); +export type Autocomplete = T | (AutocompletePrimitiveBaseType & Record) diff --git a/types/webidl.d.ts b/types/webidl.d.ts index 8a23a85bf01..99b97013c20 100644 --- a/types/webidl.d.ts +++ b/types/webidl.d.ts @@ -150,7 +150,7 @@ interface WebidlConverters { ): NodeJS.TypedArray | ArrayBufferLike | DataView ['sequence']: SequenceConverter - + ['sequence>']: SequenceConverter ['record']: RecordConverter diff --git a/types/websocket.d.ts b/types/websocket.d.ts index d1be45235d4..a961914eb9f 100644 --- a/types/websocket.d.ts +++ b/types/websocket.d.ts @@ -24,7 +24,7 @@ interface WebSocketEventMap { interface WebSocket extends EventTarget { binaryType: BinaryType - + readonly bufferedAmount: number readonly extensions: string