From 8325408834b04d14c340b03acb15731e47d3b444 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Fri, 15 Dec 2023 19:24:17 -0500 Subject: [PATCH] lib/request-browser: better usage of the fetch api. --- lib/request-browser.js | 44 +++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/lib/request-browser.js b/lib/request-browser.js index 2d9a24b..d862996 100644 --- a/lib/request-browser.js +++ b/lib/request-browser.js @@ -29,7 +29,8 @@ class RequestOptions { this.port = 80; this.path = '/'; this.query = ''; - this.agent = 'brq'; + this.pool = false; + this.agent = null; this.lookup = null; this.type = null; @@ -102,6 +103,11 @@ class RequestOptions { this.password = options.password; } + if (options.pool != null) { + assert(typeof options.pool === 'boolean'); + this.pool = options.pool; + } + if (options.agent != null) { assert(typeof options.agent === 'string'); this.agent = options.agent; @@ -249,24 +255,33 @@ class RequestOptions { getHeaders() { const headers = new FetchHeaders(); - headers.append('User-Agent', this.agent); + let referrer = 'no-referrer'; + + // https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name + if (this.agent != null) + headers.append('User-Agent', this.agent); if (this.type) headers.append('Content-Type', mime.type(this.type)); - if (this.body) - headers.append('Content-Length', this.body.length.toString(10)); - if (this.username || this.password) { const auth = `${this.username}:${this.password}`; const data = Buffer.from(auth, 'utf8'); headers.append('Authorization', `Basic ${data.toString('base64')}`); } - for (const name of Object.keys(this.headers)) + for (const name of Object.keys(this.headers)) { + switch (name.toLowerCase()) { + case 'referer': + case 'referrer': + referrer = this.headers[name]; + continue; + } + headers.append(name, this.headers[name]); + } - return headers; + return [headers, referrer]; } toURL() { @@ -292,19 +307,26 @@ class RequestOptions { } toHTTP() { + // https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#parameters + // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode + // https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials + const auth = this.username || this.password; + const [headers, referrer] = this.getHeaders(); + return { method: this.method, - headers: this.getHeaders(), + headers, body: this.body ? new Uint8Array(this.body.buffer, this.body.byteOffset, this.body.byteLength) : null, mode: 'cors', - credentials: 'include', - cache: 'no-cache', + credentials: auth ? 'include' : 'same-origin', + cache: 'no-store', redirect: 'follow', - referrer: 'no-referrer' + referrer, + keepalive: this.pool }; } }