forked from web-std/io
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathrequest.js
330 lines (280 loc) · 7.78 KB
/
request.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/**
* Request.js
*
* Request class contains server only options
*
* All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
*/
import {format as formatUrl} from 'url';
import {AbortController as AbortControllerPolyfill} from 'abort-controller';
import Headers from './headers.js';
import Body, {clone, extractContentType, getTotalBytes} from './body.js';
import {isAbortSignal} from './utils/is.js';
import {getSearch} from './utils/get-search.js';
const INTERNALS = Symbol('Request internals');
/**
* Check if `obj` is an instance of Request.
*
* @param {any} object
* @return {object is Request}
*/
const isRequest = object => {
return (
typeof object === 'object' &&
typeof object[INTERNALS] === 'object'
);
};
/**
* Request class
* @implements {globalThis.Request}
*
* @typedef {Object} RequestState
* @property {string} method
* @property {RequestRedirect} redirect
* @property {globalThis.Headers} headers
* @property {URL} parsedURL
* @property {AbortSignal|null} signal
*
* @typedef {Object} RequestExtraOptions
* @property {number} [follow]
* @property {boolean} [compress]
* @property {number} [size]
* @property {number} [counter]
* @property {Agent} [agent]
* @property {number} [highWaterMark]
* @property {boolean} [insecureHTTPParser]
*
* @typedef {((url:URL) => import('http').Agent | import('https').Agent) | import('http').Agent | import('https').Agent} Agent
*
* @typedef {Object} RequestOptions
* @property {string} [method]
* @property {ReadableStream<Uint8Array>|null} [body]
* @property {globalThis.Headers} [headers]
* @property {RequestRedirect} [redirect]
*
*/
export default class Request extends Body {
/**
* @param {string|Request|URL} info Url or Request instance
* @param {RequestInit & RequestExtraOptions} init Custom options
*/
constructor(info, init = {}) {
let parsedURL;
/** @type {RequestOptions & RequestExtraOptions} */
let settings
// Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245)
if (isRequest(info)) {
parsedURL = new URL(info.url);
settings = (info)
} else {
parsedURL = new URL(info);
settings = {};
}
let method = init.method || settings.method || 'GET';
method = method.toUpperCase();
const inputBody = init.body != null
? init.body
: (isRequest(info) && info.body !== null)
? clone(info)
: null;
// eslint-disable-next-line no-eq-null, eqeqeq
if (inputBody != null && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
super(inputBody, {
size: init.size || settings.size || 0
});
const input = settings
const headers = /** @type {globalThis.Headers} */
(new Headers(init.headers || input.headers || {}));
if (inputBody !== null && !headers.has('Content-Type')) {
const contentType = extractContentType(this);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = 'signal' in init
? init.signal
: isRequest(input)
? input.signal
: null;
// eslint-disable-next-line no-eq-null, eqeqeq
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');
}
if (!signal) {
let AbortControllerConstructor = typeof AbortController != "undefined"
? AbortController
: AbortControllerPolyfill;
/** @type {any} */
let newSignal = new AbortControllerConstructor().signal;
signal = newSignal;
}
/** @type {RequestState} */
this[INTERNALS] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal: signal || null
};
/** @type {boolean} */
this.keepalive
// Node-fetch-only options
/** @type {number} */
this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow;
/** @type {boolean} */
this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress;
/** @type {number} */
this.counter = init.counter || input.counter || 0;
/** @type {Agent|undefined} */
this.agent = init.agent || input.agent;
/** @type {number} */
this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
/** @type {boolean} */
this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
}
/**
* @type {RequestCache}
*/
get cache() {
return "default"
}
/**
* @type {RequestCredentials}
*/
get credentials() {
return "same-origin"
}
/**
* @type {RequestDestination}
*/
get destination() {
return ""
}
get integrity() {
return ""
}
/** @type {RequestMode} */
get mode() {
return "cors"
}
/** @type {string} */
get referrer() {
return ""
}
/** @type {ReferrerPolicy} */
get referrerPolicy() {
return ""
}
get method() {
return this[INTERNALS].method;
}
/**
* @type {string}
*/
get url() {
return formatUrl(this[INTERNALS].parsedURL);
}
/**
* @type {globalThis.Headers}
*/
get headers() {
return this[INTERNALS].headers;
}
get redirect() {
return this[INTERNALS].redirect;
}
/**
* @returns {AbortSignal}
*/
get signal() {
// @ts-ignore
return this[INTERNALS].signal;
}
/**
* Clone this request
*
* @return {globalThis.Request}
*/
clone() {
return new Request(this);
}
get [Symbol.toStringTag]() {
return 'Request';
}
}
Object.defineProperties(Request.prototype, {
method: {enumerable: true},
url: {enumerable: true},
headers: {enumerable: true},
redirect: {enumerable: true},
clone: {enumerable: true},
signal: {enumerable: true}
});
/**
* Convert a Request to Node.js http request options.
* The options object to be passed to http.request
*
* @param {Request & Record<INTERNALS, RequestState>} request - A Request instance
*/
export const getNodeRequestOptions = request => {
const {parsedURL} = request[INTERNALS];
const headers = new Headers(request[INTERNALS].headers);
// Fetch step 1.3
if (!headers.has('Accept')) {
headers.set('Accept', '*/*');
}
// HTTP-network-or-cache fetch steps 2.4-2.7
let contentLengthValue = null;
if (request.body === null && /^(post|put)$/i.test(request.method)) {
contentLengthValue = '0';
}
if (request.body !== null) {
const totalBytes = getTotalBytes(request);
// Set Content-Length if totalBytes is a number (that is not NaN)
if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set('Content-Length', contentLengthValue);
}
// HTTP-network-or-cache fetch step 2.11
if (!headers.has('User-Agent')) {
headers.set('User-Agent', 'node-fetch');
}
// HTTP-network-or-cache fetch step 2.15
if (request.compress && !headers.has('Accept-Encoding')) {
headers.set('Accept-Encoding', 'gzip,deflate,br');
}
let {agent} = request;
if (typeof agent === 'function') {
agent = agent(parsedURL);
}
if (!headers.has('Connection') && !agent) {
headers.set('Connection', 'close');
}
// HTTP-network fetch step 4.2
// chunked encoding is handled by Node.js
const search = getSearch(parsedURL);
// Manually spread the URL object instead of spread syntax
const requestOptions = {
path: parsedURL.pathname + search,
pathname: parsedURL.pathname,
hostname: parsedURL.hostname,
protocol: parsedURL.protocol,
port: parsedURL.port,
hash: parsedURL.hash,
search: parsedURL.search,
// @ts-ignore - it does not has a query
query: parsedURL.query,
href: parsedURL.href,
method: request.method,
// @ts-ignore - not sure what this supposed to do
headers: headers[Symbol.for('nodejs.util.inspect.custom')](),
insecureHTTPParser: request.insecureHTTPParser,
agent
};
return requestOptions;
};