Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
"mime-types": "^2.1.35",
"qs": "^6.15.0",
"type-fest": "^4.41.0",
"undici": "^7.24.0",
"undici": "^8.2.0",
"ylru": "^2.0.0"
},
"devDependencies": {
Expand Down Expand Up @@ -109,7 +109,7 @@
}
},
"engines": {
"node": ">= 22.0.0"
"node": ">= 22.19.0"
},
"packageManager": "pnpm@11.0.8",
"pnpm": {
Expand Down
12 changes: 6 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/BaseAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ export class BaseAgent extends Agent {
#opaqueLocalStorage?: AsyncLocalStorage<FetchOpaque>;

constructor(options: BaseAgentOptions) {
super(options);
super({
...options,
allowH2: options.allowH2 ?? false,
});
this.#opaqueLocalStorage = options.opaqueLocalStorage;
}

Expand Down
2 changes: 1 addition & 1 deletion src/HttpAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class HttpAgent extends BaseAgent {
};
super({
...baseOpts,
connect: { ...options.connect, lookup: lookupFunction, allowH2: options.allowH2 },
connect: { ...options.connect, lookup: lookupFunction, allowH2: options.allowH2 ?? false },
});
this.#checkAddress = options.checkAddress;
}
Expand Down
10 changes: 5 additions & 5 deletions src/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,22 +187,22 @@ export class HttpClient extends EventEmitter {
constructor(clientOptions?: ClientOptions) {
super();
this.#defaultArgs = clientOptions?.defaultArgs;
const allowH2 = clientOptions?.allowH2 ?? false;
if (clientOptions?.lookup || clientOptions?.checkAddress) {
this.#dispatcher = new HttpAgent({
lookup: clientOptions.lookup,
checkAddress: clientOptions.checkAddress,
connect: clientOptions.connect,
allowH2: clientOptions.allowH2,
allowH2,
});
} else if (clientOptions?.connect) {
this.#dispatcher = new Agent({
connect: clientOptions.connect,
allowH2: clientOptions.allowH2,
allowH2,
});
} else if (clientOptions?.allowH2) {
// Support HTTP2
} else {
this.#dispatcher = new Agent({
allowH2: clientOptions.allowH2,
allowH2,
});
}
initDiagnosticsChannel();
Expand Down
2 changes: 1 addition & 1 deletion src/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export type RequestURL = string | URL;
export type FixJSONCtlCharsHandler = (data: string) => string;
export type FixJSONCtlChars = boolean | FixJSONCtlCharsHandler;

type AbortSignal = unknown;
type AbortSignal = globalThis.AbortSignal;

export type RequestOptions = {
/** Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'. */
Expand Down
1 change: 1 addition & 0 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export class FetchFactory {

setClientOptions(clientOptions: ClientOptions): void {
let dispatcherOption: BaseAgentOptions = {
allowH2: clientOptions.allowH2 ?? false,
opaqueLocalStorage: this.#opaqueLocalStorage,
};
let dispatcherClazz: new (options: BaseAgentOptions) => BaseAgent = BaseAgent;
Expand Down
43 changes: 43 additions & 0 deletions test/HttpClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,49 @@ describe('HttpClient.test.ts', () => {
assert(httpClient.getDispatcherPoolStats()[_url.substring(0, _url.length - 1)].connected > 1);
});

it('should keep HTTP/1.1 by default', async () => {
const server = createSecureServer({
allowHTTP1: true,
key: pems.private,
cert: pems.cert,
});

let lastHttpVersion = '';
server.on('request', (req, res) => {
lastHttpVersion = req.httpVersion;
res.writeHead(200, {
'content-type': 'text/plain; charset=utf-8',
});
res.end(`hello http/${req.httpVersion}!`);
});

server.listen(0);
await once(server, 'listening');

const httpClient = new HttpClient({
connect: {
rejectUnauthorized: false,
},
});

const url = `https://localhost:${(server.address() as AddressInfo).port}`;
try {
const response = await httpClient.request<string>(url, {
dataType: 'text',
});
assert.equal(response.status, 200);
assert.equal(response.data, 'hello http/1.1!');
assert.equal(lastHttpVersion, '1.1');
} finally {
await new Promise<void>((resolve, reject) => {
server.close((err) => {
if (err) reject(err);
else resolve();
});
});
}
});

it('should not exit after other side closed error', async () => {
const server = createSecureServer({
key: pems.private,
Expand Down
49 changes: 49 additions & 0 deletions test/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import assert from 'node:assert/strict';
import diagnosticsChannel from 'node:diagnostics_channel';
import { once } from 'node:events';
import { createSecureServer } from 'node:http2';
import type { AddressInfo } from 'node:net';
import { setTimeout as sleep } from 'node:timers/promises';

import selfsigned from 'selfsigned';
import { Request } from 'undici';
import { describe, it, beforeAll, afterAll } from 'vite-plus/test';

Expand Down Expand Up @@ -113,6 +117,51 @@ describe('fetch.test.ts', () => {
assert(Object.keys(stats).length > 0, `dispatcher pool stats: ${JSON.stringify(stats)}`);
});

it('fetch should keep HTTP/1.1 by default', async () => {
const pem = selfsigned.generate([], {
keySize: 2048,
});
const server = createSecureServer({
allowHTTP1: true,
key: pem.private,
cert: pem.cert,
});

let lastHttpVersion = '';
server.on('request', (req, res) => {
lastHttpVersion = req.httpVersion;
res.writeHead(200, {
'content-type': 'text/plain; charset=utf-8',
});
res.end(`hello http/${req.httpVersion}!`);
});

server.listen(0);
await once(server, 'listening');

const factory = new FetchFactory();
factory.setClientOptions({
connect: {
rejectUnauthorized: false,
},
});

const url = `https://localhost:${(server.address() as AddressInfo).port}`;
try {
const response = await factory.fetch(url);
assert.equal(response.status, 200);
assert.equal(await response.text(), 'hello http/1.1!');
assert.equal(lastHttpVersion, '1.1');
} finally {
await new Promise<void>((resolve, reject) => {
server.close((err) => {
if (err) reject(err);
else resolve();
});
});
}
});

it('fetch request with post should work', async () => {
await assert.doesNotReject(async () => {
const request = new Request(_url, {
Expand Down
46 changes: 30 additions & 16 deletions test/options.dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ describe('options.dispatcher.test.ts', () => {
let _url: string;
let proxyServer: any;
let proxyServerUrl: string;
const proxyAgents: ProxyAgent[] = [];
beforeAll(async () => {
const { closeServer, url } = await startServer();
close = closeServer;
Expand All @@ -27,34 +28,47 @@ describe('options.dispatcher.test.ts', () => {

afterAll(async () => {
await close();
await Promise.all(proxyAgents.map((proxyAgent) => proxyAgent.close()));
await new Promise((resolve) => {
proxyServer.close(resolve);
});
});

it('should work with proxyAgent dispatcher', async () => {
const proxyAgent = new ProxyAgent(proxyServerUrl);
const response = await request(`${_url}html`, {
dispatcher: proxyAgent,
dataType: 'text',
timing: true,
});
assert.equal(response.status, 200);
assert.equal(response.data, '<h1>hello</h1>');
const { closeServer: closeHttpsServer, url: httpsUrl } = await startServer({ https: true });
try {
const proxyAgent = new ProxyAgent({
uri: proxyServerUrl,
requestTls: {
rejectUnauthorized: false,
},
});
proxyAgents.push(proxyAgent);
const response = await request(`${_url}html`, {
dispatcher: proxyAgent,
dataType: 'text',
timing: true,
});
assert.equal(response.status, 200);
assert.equal(response.data, '<h1>hello</h1>');

const response2 = await request('https://registry.npmmirror.com/urllib/latest', {
dispatcher: proxyAgent,
dataType: 'json',
timing: true,
});
// console.log(response2.status, response2.headers);
assert.equal(response2.status, 200);
assert.equal(response2.data.name, 'urllib');
const response2 = await request(httpsUrl, {
dispatcher: proxyAgent,
dataType: 'json',
timing: true,
});
assert.equal(response2.status, 200);
assert.equal(response2.data.method, 'GET');
assert.equal(response2.data.headers.host, new URL(httpsUrl).host);
} finally {
await closeHttpsServer();
}
});

it('should work with getGlobalDispatcher() dispatcher', async () => {
const agent = getGlobalDispatcher();
const proxyAgent = new ProxyAgent(proxyServerUrl);
proxyAgents.push(proxyAgent);
setGlobalDispatcher(proxyAgent);
const response = await request(`${_url}html`, {
dataType: 'text',
Expand Down
Loading