@wiajs/request 3.0.35 → 3.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/request.cjs CHANGED
@@ -1,179 +1,158 @@
1
1
  /*!
2
- * wia request v3.0.35
2
+ * wia request v3.0.36
3
3
  * (c) 2022-2025 Sibyl Yu and contributors
4
4
  * Released under the MIT License.
5
5
  */
6
6
  'use strict';
7
7
 
8
- const stream = require('node:stream');
9
8
  const log$2 = require('@wiajs/log');
9
+ const stream = require('stream');
10
+ const assert = require('assert');
11
+ const http = require('http');
12
+ const https = require('https');
10
13
  const mime = require('mime-types');
11
- const assert = require('node:assert');
12
- const http = require('node:http');
13
- const https = require('node:https');
14
- const url = require('node:url');
15
- const zlib = require('node:zlib');
14
+ const stream$1 = require('node:stream');
15
+ const url = require('url');
16
+ const zlib = require('zlib');
16
17
 
17
18
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
18
- class ZlibTransform extends stream.Transform {
19
- /**
20
- *
21
- * @param {*} chunk
22
- * @param {*} encoding
23
- * @param {*} callback
24
- */
25
- __transform(chunk, encoding, callback) {
26
- this.push(chunk);
27
- callback();
28
- }
29
-
30
- /**
31
- *
32
- * @param {*} chunk
33
- * @param {*} encoding
34
- * @param {*} callback
35
- */
36
- _transform(chunk, encoding, callback) {
37
- if (chunk.length !== 0) {
38
- this._transform = this.__transform;
39
-
40
- // Add Default Compression headers if no zlib headers are present
41
- if (chunk[0] !== 120) {
42
- // Hex: 78
43
- const header = Buffer.alloc(2);
44
- header[0] = 120; // Hex: 78
45
- header[1] = 156; // Hex: 9C
46
- this.push(header, encoding);
47
- }
48
- }
49
-
50
- this.__transform(chunk, encoding, callback);
51
- }
52
- }
19
+ let ZlibTransform = class ZlibTransform extends stream.Transform {
20
+ /**
21
+ *
22
+ * @param {*} chunk
23
+ * @param {*} encoding
24
+ * @param {*} callback
25
+ */ __transform(chunk, encoding, callback) {
26
+ this.push(chunk);
27
+ callback();
28
+ }
29
+ /**
30
+ *
31
+ * @param {*} chunk
32
+ * @param {*} encoding
33
+ * @param {*} callback
34
+ */ _transform(chunk, encoding, callback) {
35
+ if (chunk.length !== 0) {
36
+ this._transform = this.__transform;
37
+ // Add Default Compression headers if no zlib headers are present
38
+ if (chunk[0] !== 120) {
39
+ // Hex: 78
40
+ const header = Buffer.alloc(2);
41
+ header[0] = 120 // Hex: 78
42
+ ;
43
+ header[1] = 156 // Hex: 9C
44
+ ;
45
+ this.push(header, encoding);
46
+ }
47
+ }
48
+ this.__transform(chunk, encoding, callback);
49
+ }
50
+ };
53
51
 
54
- class Caseless {
55
- /**
56
- * @param {*} dict
57
- */
58
- constructor(dict) {
59
- this.dict = dict || {};
60
- }
61
-
62
- /**
52
+ let Caseless = class Caseless {
53
+ /**
63
54
  *
64
55
  * @param {*} name
65
56
  * @param {*} value
66
57
  * @param {*} clobber
67
58
  * @returns
68
- */
69
- set(name, value, clobber) {
70
- if (typeof name === 'object') {
71
- for (const n of name) {
72
- this.set(n, name[n], value);
73
- }
74
- } else {
75
- if (typeof clobber === 'undefined') clobber = true;
76
- const has = this.has(name);
77
-
78
- if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value;
79
- else this.dict[has || name] = value;
80
- return has
81
- }
82
- }
83
-
84
- /**
59
+ */ set(name, value, clobber) {
60
+ if (typeof name === 'object') {
61
+ for (const n of name){
62
+ this.set(n, name[n], value);
63
+ }
64
+ } else {
65
+ if (typeof clobber === 'undefined') clobber = true;
66
+ const has = this.has(name);
67
+ if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value;
68
+ else this.dict[has || name] = value;
69
+ return has;
70
+ }
71
+ }
72
+ /**
73
+ *
74
+ * @param {string} name
75
+ * @returns
76
+ */ has(name) {
77
+ const keys = Object.keys(this.dict);
78
+ name = name.toLowerCase();
79
+ for(let i = 0; i < keys.length; i++){
80
+ if (keys[i].toLowerCase() === name) return keys[i];
81
+ }
82
+ return false;
83
+ }
84
+ /**
85
85
  *
86
86
  * @param {string} name
87
87
  * @returns
88
- */
89
- has(name) {
90
- const keys = Object.keys(this.dict);
91
- name = name.toLowerCase();
92
- for (let i = 0; i < keys.length; i++) {
93
- if (keys[i].toLowerCase() === name) return keys[i]
94
- }
95
- return false
96
- }
97
-
98
- /**
88
+ */ get(name) {
89
+ name = name.toLowerCase();
90
+ let result;
91
+ let _key;
92
+ const headers = this.dict;
93
+ for (const key of Object.keys(headers)){
94
+ _key = key.toLowerCase();
95
+ if (name === _key) result = headers[key];
96
+ }
97
+ return result;
98
+ }
99
+ /**
99
100
  *
100
101
  * @param {string} name
101
102
  * @returns
102
- */
103
- get(name) {
104
- name = name.toLowerCase();
105
- let result;
106
- let _key;
107
- const headers = this.dict;
108
- for (const key of Object.keys(headers)) {
109
- _key = key.toLowerCase();
110
- if (name === _key) result = headers[key];
111
- }
112
- return result
113
- }
114
-
115
- /**
103
+ */ swap(name) {
104
+ const has = this.has(name);
105
+ if (has === name) return;
106
+ if (!has) throw new Error('There is no header than matches "' + name + '"');
107
+ this.dict[name] = this.dict[has];
108
+ delete this.dict[has];
109
+ }
110
+ /**
116
111
  *
117
112
  * @param {string} name
118
113
  * @returns
119
- */
120
- swap(name) {
121
- const has = this.has(name);
122
- if (has === name) return
123
- if (!has) throw new Error('There is no header than matches "' + name + '"')
124
- this.dict[name] = this.dict[has];
125
- delete this.dict[has];
126
- }
127
-
128
- /**
129
- *
130
- * @param {string} name
131
- * @returns
132
- */
133
- del(name) {
134
- name = String(name).toLowerCase();
135
- let deleted = false;
136
- let changed = 0;
137
- const dict = this.dict;
138
- for (const key of Object.keys(this.dict)) {
139
- if (name === String(key).toLowerCase()) {
140
- deleted = delete dict[key];
141
- changed += 1;
142
- }
143
- }
144
- return changed === 0 ? true : deleted
145
- }
146
- }
114
+ */ del(name) {
115
+ name = String(name).toLowerCase();
116
+ let deleted = false;
117
+ let changed = 0;
118
+ const dict = this.dict;
119
+ for (const key of Object.keys(this.dict)){
120
+ if (name === String(key).toLowerCase()) {
121
+ deleted = delete dict[key];
122
+ changed += 1;
123
+ }
124
+ }
125
+ return changed === 0 ? true : deleted;
126
+ }
127
+ /**
128
+ * @param {*} dict
129
+ */ constructor(dict){
130
+ this.dict = dict || {};
131
+ }
132
+ };
147
133
 
148
- /**
149
- * utils for request
150
- */
151
-
152
- const {URL: URL$1} = url;
153
-
154
- // Whether to use the native URL object or the legacy url module
155
- let useNativeURL = false;
156
- try {
157
- assert(new URL$1(''));
158
- } catch (error) {
159
- useNativeURL = error.code === 'ERR_INVALID_URL';
160
- }
161
-
162
- // URL fields to preserve in copy operations
163
- const preservedUrlFields = [
164
- 'auth',
165
- 'host',
166
- 'hostname',
167
- 'href',
168
- 'path',
169
- 'pathname',
170
- 'port',
171
- 'protocol',
172
- 'query',
173
- 'search',
174
- 'hash',
175
- ];
176
-
134
+ const { URL: URL$1 } = url;
135
+ // Whether to use the native URL object or the legacy url module
136
+ let useNativeURL = false;
137
+ try {
138
+ assert(new URL$1(''));
139
+ } catch (error) {
140
+ useNativeURL = error.code === 'ERR_INVALID_URL';
141
+ }
142
+ // URL fields to preserve in copy operations
143
+ const preservedUrlFields = [
144
+ 'auth',
145
+ 'host',
146
+ 'hostname',
147
+ 'href',
148
+ 'path',
149
+ 'pathname',
150
+ 'port',
151
+ 'protocol',
152
+ 'query',
153
+ 'search',
154
+ 'hash'
155
+ ];
177
156
  /**
178
157
  * Create a custom error type.
179
158
  * @param {string} code - The error code.
@@ -185,272 +164,221 @@ const preservedUrlFields = [
185
164
  * @property {string} code - The error code.
186
165
  * @property {string} message - The error message.
187
166
  * @property {Error | undefined} cause - The optional error cause.
188
- */
189
- function createErrorType(code, message, baseClass) {
190
- /**
167
+ */ function createErrorType(code, message, baseClass) {
168
+ /**
191
169
  * Create constructor
192
170
  * @param {*} properties
193
- */
194
- function CustomError(properties) {
195
- // istanbul ignore else
196
- if (isFunction(Error.captureStackTrace)) {
197
- Error.captureStackTrace(this, this.constructor);
198
- }
199
- Object.assign(this, properties || {});
200
- this.code = code;
201
- // @ts-ignore
202
- this.message = this.cause ? `${message}: ${this.cause.message}` : message;
203
- }
204
-
205
- // Attach constructor and set default properties
206
- CustomError.prototype = new (baseClass || Error)();
207
- Object.defineProperties(CustomError.prototype, {
208
- constructor: {
209
- value: CustomError,
210
- enumerable: false,
211
- },
212
- name: {
213
- value: `Error [${code}]`,
214
- enumerable: false,
215
- },
216
- });
217
-
218
- // @ts-ignore
219
- return CustomError
220
- }
221
-
222
- const InvalidUrlError = createErrorType('ERR_INVALID_URL', 'Invalid URL', TypeError);
223
-
224
- // @ts-ignore
225
- const typeOfTest = type => thing => typeof thing === type;
226
-
171
+ */ function CustomError(properties) {
172
+ // istanbul ignore else
173
+ if (isFunction(Error.captureStackTrace)) {
174
+ Error.captureStackTrace(this, this.constructor);
175
+ }
176
+ Object.assign(this, properties || {});
177
+ this.code = code;
178
+ // @ts-ignore
179
+ this.message = this.cause ? `${message}: ${this.cause.message}` : message;
180
+ }
181
+ // Attach constructor and set default properties
182
+ CustomError.prototype = new (baseClass || Error)();
183
+ Object.defineProperties(CustomError.prototype, {
184
+ constructor: {
185
+ value: CustomError,
186
+ enumerable: false
187
+ },
188
+ name: {
189
+ value: `Error [${code}]`,
190
+ enumerable: false
191
+ }
192
+ });
193
+ // @ts-ignore
194
+ return CustomError;
195
+ }
196
+ const InvalidUrlError = createErrorType('ERR_INVALID_URL', 'Invalid URL', TypeError);
197
+ // @ts-ignore
198
+ const typeOfTest = (type)=>(thing)=>typeof thing === type;
227
199
  /**
228
200
  * Determine if a value is a String
229
201
  *
230
202
  * @param {*} val The value to test
231
203
  *
232
204
  * @returns {boolean} True if value is a String, otherwise false
233
- */
234
- const isString = typeOfTest('string');
235
-
205
+ */ const isString = typeOfTest('string');
236
206
  /**
237
207
  * Determine if a value is an Array
238
208
  *
239
209
  * @param {Object} val The value to test
240
210
  *
241
211
  * @returns {boolean} True if value is an Array, otherwise false
242
- */
243
- const {isArray} = Array;
244
-
212
+ */ const { isArray } = Array;
245
213
  /**
246
214
  * Determine if a value is undefined
247
215
  *
248
216
  * @param {*} val The value to test
249
217
  *
250
218
  * @returns {boolean} True if the value is undefined, otherwise false
251
- */
252
- const isUndefined = typeOfTest('undefined');
253
-
219
+ */ const isUndefined = typeOfTest('undefined');
254
220
  /**
255
221
  * Determine if a value is a Buffer
256
222
  *
257
223
  * @param {*} val The value to test
258
224
  *
259
225
  * @returns {boolean} True if value is a Buffer, otherwise false
260
- */
261
- function isBuffer(val) {
262
- return (
263
- val !== null &&
264
- !isUndefined(val) &&
265
- val.constructor !== null &&
266
- !isUndefined(val.constructor) &&
267
- isFunction(val.constructor.isBuffer) &&
268
- val.constructor.isBuffer(val)
269
- )
270
- }
271
-
226
+ */ function isBuffer(val) {
227
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
228
+ }
272
229
  /**
273
230
  * Determine if a value is a Function
274
231
  *
275
232
  * @param {*} val The value to test
276
233
  * @returns {boolean} True if value is a Function, otherwise false
277
- */
278
- const isFunction = typeOfTest('function');
279
-
234
+ */ const isFunction = typeOfTest('function');
280
235
  /**
281
236
  * Determine if a value is a Number
282
237
  *
283
238
  * @param {*} val The value to test
284
239
  *
285
240
  * @returns {boolean} True if value is a Number, otherwise false
286
- */
287
- const isNumber = typeOfTest('number');
288
-
241
+ */ const isNumber = typeOfTest('number');
289
242
  /**
290
243
  * Determine if a value is an Object
291
244
  *
292
245
  * @param {*} thing The value to test
293
246
  *
294
247
  * @returns {boolean} True if value is an Object, otherwise false
295
- */
296
- const isObject = thing => thing !== null && typeof thing === 'object';
297
-
248
+ */ const isObject = (thing)=>thing !== null && typeof thing === 'object';
298
249
  /**
299
250
  * Determine if a value is a Boolean
300
251
  *
301
252
  * @param {*} thing The value to test
302
253
  * @returns {boolean} True if value is a Boolean, otherwise false
303
- */
304
- const isBoolean = thing => thing === true || thing === false;
305
-
306
- const noop = () => {};
307
-
254
+ */ const isBoolean = (thing)=>thing === true || thing === false;
255
+ const noop = ()=>{};
308
256
  /**
309
257
  *
310
258
  * @param {*} value
311
259
  * @returns
312
- */
313
- function isURL(value) {
314
- return URL$1 && value instanceof URL$1
315
- }
316
-
260
+ */ function isURL(value) {
261
+ return URL$1 && value instanceof URL$1;
262
+ }
317
263
  /**
318
264
  *
319
265
  * @param {*} rs
320
266
  * @returns
321
- */
322
- function isReadStream(rs) {
323
- return rs.readable && rs.path && rs.mode
324
- }
325
-
267
+ */ function isReadStream(rs) {
268
+ return rs.readable && rs.path && rs.mode;
269
+ }
326
270
  /**
327
271
  *
328
272
  * @param {*} urlObject
329
273
  * @param {*} target
330
274
  * @returns
331
- */
332
- function spreadUrlObject(urlObject, target) {
333
- const spread = target || {};
334
- for (const key of preservedUrlFields) {
335
- spread[key] = urlObject[key];
336
- }
337
-
338
- // Fix IPv6 hostname
339
- if (spread.hostname.startsWith('[')) {
340
- spread.hostname = spread.hostname.slice(1, -1);
341
- }
342
- // Ensure port is a number
343
- if (spread.port !== '') {
344
- spread.port = Number(spread.port);
345
- }
346
- // Concatenate path
347
- spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
348
-
349
- return spread
350
- }
351
-
275
+ */ function spreadUrlObject(urlObject, target) {
276
+ const spread = target || {};
277
+ for (const key of preservedUrlFields){
278
+ spread[key] = urlObject[key];
279
+ }
280
+ // Fix IPv6 hostname
281
+ if (spread.hostname.startsWith('[')) {
282
+ spread.hostname = spread.hostname.slice(1, -1);
283
+ }
284
+ // Ensure port is a number
285
+ if (spread.port !== '') {
286
+ spread.port = Number(spread.port);
287
+ }
288
+ // Concatenate path
289
+ spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
290
+ return spread;
291
+ }
352
292
  /**
353
293
  *
354
294
  * @param {*} input
355
295
  * @returns
356
- */
357
- function parseUrl(input) {
358
- let parsed;
359
- // istanbul ignore else
360
- if (useNativeURL) {
361
- parsed = new URL$1(input);
362
- } else {
363
- // Ensure the URL is valid and absolute
364
- parsed = validateUrl(url.parse(input));
365
- if (!isString(parsed.protocol)) {
366
- throw new InvalidUrlError({input})
367
- }
368
- }
369
- return parsed
370
- }
371
-
296
+ */ function parseUrl(input) {
297
+ let parsed;
298
+ // istanbul ignore else
299
+ if (useNativeURL) {
300
+ parsed = new URL$1(input);
301
+ } else {
302
+ // Ensure the URL is valid and absolute
303
+ parsed = validateUrl(url.parse(input));
304
+ if (!isString(parsed.protocol)) {
305
+ throw new InvalidUrlError({
306
+ input
307
+ });
308
+ }
309
+ }
310
+ return parsed;
311
+ }
372
312
  /**
373
313
  *
374
314
  * @param {*} input
375
315
  * @returns
376
- */
377
- function validateUrl(input) {
378
- if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
379
- throw new InvalidUrlError({input: input.href || input})
380
- }
381
- if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
382
- throw new InvalidUrlError({input: input.href || input})
383
- }
384
- return input
385
- }
386
-
316
+ */ function validateUrl(input) {
317
+ if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
318
+ throw new InvalidUrlError({
319
+ input: input.href || input
320
+ });
321
+ }
322
+ if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
323
+ throw new InvalidUrlError({
324
+ input: input.href || input
325
+ });
326
+ }
327
+ return input;
328
+ }
387
329
  /**
388
330
  *
389
331
  * @param {*} relative
390
332
  * @param {*} base
391
333
  * @returns
392
- */
393
- function resolveUrl(relative, base) {
394
- // istanbul ignore next
395
- return useNativeURL ? new URL$1(relative, base) : parseUrl(url.resolve(base, relative))
396
- }
397
-
334
+ */ function resolveUrl(relative, base) {
335
+ // istanbul ignore next
336
+ return useNativeURL ? new URL$1(relative, base) : parseUrl(url.resolve(base, relative));
337
+ }
398
338
  /**
399
339
  *
400
340
  * @param {string} method
401
341
  * @param {number} code
402
342
  * @returns
403
- */
404
- function noBody(method, code) {
405
- return (
406
- method === 'HEAD' ||
407
- // Informational
408
- (code >= 100 && code < 200) ||
409
- // No Content
410
- code === 204 ||
411
- // Not Modified
412
- code === 304
413
- )
414
- }
415
-
343
+ */ function noBody(method, code) {
344
+ return method === 'HEAD' || // Informational
345
+ code >= 100 && code < 200 || // No Content
346
+ code === 204 || // Not Modified
347
+ code === 304;
348
+ }
416
349
  /**
417
350
  * Determine if a value is a Stream
418
351
  *
419
352
  * @param {*} val The value to test
420
353
  *
421
354
  * @returns {boolean} True if value is a Stream, otherwise false
422
- */
423
- const isStream = val => isObject(val) && isFunction(val.pipe);
424
-
425
- const utils = {
426
- createErrorType,
427
- InvalidUrlError,
428
- isString,
429
- isArray,
430
- isBuffer,
431
- isUndefined,
432
- isNumber,
433
- isBoolean,
434
- isFunction,
435
- isObject,
436
- isURL,
437
- isReadStream,
438
- isStream,
439
- noop,
440
- parseUrl,
441
- spreadUrlObject,
442
- validateUrl,
443
- resolveUrl,
444
- noBody,
355
+ */ const isStream = (val)=>isObject(val) && isFunction(val.pipe);
356
+ const utils = {
357
+ createErrorType,
358
+ InvalidUrlError,
359
+ isString,
360
+ isArray,
361
+ isBuffer,
362
+ isUndefined,
363
+ isNumber,
364
+ isBoolean,
365
+ isFunction,
366
+ isObject,
367
+ isURL,
368
+ isReadStream,
369
+ isStream,
370
+ noop,
371
+ parseUrl,
372
+ spreadUrlObject,
373
+ validateUrl,
374
+ resolveUrl,
375
+ noBody
445
376
  };
446
377
 
447
- /**
448
- * fork from follow-redirects
449
- * https://github.com/follow-redirects/follow-redirects
450
- */
451
-
452
- const log$1 = log$2.log({env: `wia:req:${log$2.name((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('request.cjs', document.baseURI).href)))}`}); // __filename
453
-
378
+ const log$1 = log$2.log({
379
+ env: `wia:req:${log$2.name((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('request.cjs', document.baseURI).href)))}`
380
+ }) // __filename
381
+ ;
454
382
  /**
455
383
  * @typedef {object} Opts
456
384
  * @prop {Object.<string,string>} headers
@@ -470,470 +398,267 @@ const log$1 = log$2.log({env: `wia:req:${log$2.name((typeof document === 'undefi
470
398
  * @prop {number} [maxBodyLength = -1]
471
399
  * @prop {*} [trackRedirects]
472
400
  * @prop {*} [data]
473
- */
474
-
475
- /** @typedef {object} ResponseExt
401
+ */ /** @typedef {object} ResponseExt
476
402
  * @prop {*[]} [redirects]
477
403
  * @prop {string} [responseUrl]
478
404
  * @prop {number} [responseStartTime]
479
- */
480
-
481
- /** @typedef { http.IncomingMessage & ResponseExt} Response */
482
-
483
- const httpModules = {'http:': http, 'https:': https};
484
-
485
- const zlibOptions = {
486
- flush: zlib.constants.Z_SYNC_FLUSH,
487
- finishFlush: zlib.constants.Z_SYNC_FLUSH,
488
- };
489
-
490
- const brotliOptions = {
491
- flush: zlib.constants.BROTLI_OPERATION_FLUSH,
492
- finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
493
- };
494
-
495
- const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
496
-
497
- // clientRequest 属性转发
498
- const writeProps = [
499
- 'protocol',
500
- 'method',
501
- 'path',
502
- 'host',
503
- 'reusedSocket',
504
- 'socket',
505
- 'closed',
506
- 'destroyed',
507
- 'writable',
508
- 'writableAborted',
509
- 'writableEnded',
510
- 'writableCorked',
511
- 'errored',
512
- 'writableFinished',
513
- 'writableHighWaterMark',
514
- 'writableLength',
515
- 'writableNeedDrain',
516
- 'writableObjectMode',
517
- ];
518
-
519
- // clientReq 方法转发
520
- const writeMethods = ['cork', 'flushHeaders', 'setNoDelay', 'setSocketKeepAlive'];
521
-
522
- // Create handlers that pass events from native requests
523
- // clientRequest 事件转发写事件
524
- const writeEvents = [
525
- // 'abort', // 弃用
526
- // 'aborted', // 弃用
527
- 'close',
528
- 'connect',
529
- 'continue',
530
- 'drain',
531
- // 'error', // 单独处理,未注册 'error' 事件处理程序,错误将冒泡到全局导致程序崩溃
532
- 'finish',
533
- 'information',
534
- 'pipe',
535
- // 'response', 由 processResponse 触发
536
- 'socket', // 建立连接时触发
537
- 'timeout',
538
- 'unpipe',
539
- 'upgrade',
540
- ];
541
-
542
- const writeEventEmit = Object.create(null);
543
-
544
- for (const ev of writeEvents)
545
- writeEventEmit[ev] = /** @param {...any} args */ function (...args) {
546
- const m = this; // 事件回调,this === clientRequest 实例
547
- // log('req event', {ev})
548
- m.redirectReq.emit(ev, ...args); // 内部请求req 事情转发到 Request
549
- };
550
-
551
- // stream.Readable,在响应流上转发读流取事件
552
- // data 单独处理
553
- const readEvents = ['close', 'end', 'error', 'pause', 'readable', 'resume'];
554
- const readEventEmit = Object.create(null);
555
- for (const ev of readEvents)
556
- readEventEmit[ev] = /** @param {...any} args */ function (...args) {
557
- const m = this; // 事件回调,this === clientRequest 实例
558
- // log('res event', {ev})
559
- m.redirectReq.emit(ev, ...args); // 向上触发事件
560
- };
561
-
562
- // Error types with codes
563
- const RedirectionError = utils.createErrorType(
564
- 'ERR_FR_REDIRECTION_FAILURE',
565
- 'Redirected request failed'
566
- );
567
-
568
- const TooManyRedirectsError = utils.createErrorType(
569
- 'ERR_FR_TOO_MANY_REDIRECTS',
570
- 'Maximum number of redirects exceeded',
571
- RedirectionError
572
- );
573
-
574
- const MaxBodyLengthExceededError = utils.createErrorType(
575
- 'ERR_FR_MAX_BODY_LENGTH_EXCEEDED',
576
- 'Request body larger than maxBodyLength limit'
577
- );
578
-
579
- const WriteAfterEndError = utils.createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
580
-
581
- // request err
582
- const HostNotfoundError = utils.createErrorType('ERR_HOSTNOTFOUND', 'DNS 解析失败,主机名可能无效');
583
- const ConnRefusedError = utils.createErrorType(
584
- 'ERR_CONNREFUSED',
585
- '连接被拒绝,目标服务器可能不可用'
586
- );
587
- const ConnTimedoutError = utils.createErrorType(
588
- 'ERR_CONNTIMEDOUT',
589
- '请求超时,请检查网络连接或服务器负载'
590
- );
591
- const ConnResetError = utils.createErrorType(
592
- 'ERR_CONNRESET',
593
- '连接被重置,可能是网络问题或服务器关闭了连接'
594
- );
595
-
596
- /**
597
- * An HTTP(S) request that can be redirected
598
- * wrap http.ClientRequest
599
- */
600
- class Request extends stream.Duplex {
601
- /** @type {NodeJS.Timeout} */
602
- _timeout = null
603
- /** @type {*} */
604
- socket = null
605
- /** @type {http.ClientRequest} */
606
- _currentRequest = null
607
- /** @type {Response} */
608
- response = null
609
- /** @type {stream.Readable} */
610
- responseStream = null
611
- timing = false
612
- responseStarted = false
613
- responseStartTime = 0
614
- _destdata = false
615
- _paused = false
616
- _respended = false
617
- /** @type {stream.Readable} */
618
- pipesrc = null // 被 pipe 时的 src stream
619
- /** @type {stream.Writable[]} */
620
- pipedests = [] // pipe dest
621
- /** @type {*} */
622
- startTimer = null
623
- /** @type {Opts} */
624
- opt
625
- /** @type {*} */
626
- pipefilter
627
- /** @type {string} */
628
- _currentUrl
629
-
630
- /**
631
- * responseCallback 原消息处理回调
632
- * @param {Opts} opts
633
- * @param {*} resCallback
634
- */
635
- constructor(opts, resCallback) {
636
- super();
637
- const m = this;
638
-
639
- // log({opts}, 'new Request')
640
-
641
- // Initialize the request
642
- m.sanitizeOptions(opts);
643
- m.opt = opts;
644
- m.headers = opts.headers;
645
-
646
- // log({opts}, 'constructor')
647
-
648
- m._ended = false;
649
- m._ending = false;
650
- m._redirectCount = 0;
651
- /** @type {any[]} */
652
- m._redirects = [];
653
- m._requestBodyLength = 0;
654
- /** @type {any[]} */
655
- m._requestBodyBuffers = [];
656
-
657
- // save the callback if passed
658
- m.resCallback = resCallback;
659
-
405
+ */ /** @typedef { http.IncomingMessage & ResponseExt} Response */ const httpModules = {
406
+ 'http:': http,
407
+ 'https:': https
408
+ };
409
+ const zlibOptions = {
410
+ flush: zlib.constants.Z_SYNC_FLUSH,
411
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
412
+ };
413
+ const brotliOptions = {
414
+ flush: zlib.constants.BROTLI_OPERATION_FLUSH,
415
+ finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
416
+ };
417
+ const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
418
+ // clientRequest 属性转发
419
+ const writeProps = [
420
+ 'protocol',
421
+ 'method',
422
+ 'path',
423
+ 'host',
424
+ 'reusedSocket',
425
+ 'socket',
426
+ 'closed',
427
+ 'destroyed',
428
+ 'writable',
429
+ 'writableAborted',
430
+ 'writableEnded',
431
+ 'writableCorked',
432
+ 'errored',
433
+ 'writableFinished',
434
+ 'writableHighWaterMark',
435
+ 'writableLength',
436
+ 'writableNeedDrain',
437
+ 'writableObjectMode'
438
+ ];
439
+ // clientReq 方法转发
440
+ const writeMethods = [
441
+ 'cork',
442
+ 'flushHeaders',
443
+ 'setNoDelay',
444
+ 'setSocketKeepAlive'
445
+ ];
446
+ // Create handlers that pass events from native requests
447
+ // 在 clientRequest 事件转发写事件
448
+ const writeEvents = [
449
+ // 'abort', // 弃用
450
+ // 'aborted', // 弃用
451
+ 'close',
452
+ 'connect',
453
+ 'continue',
454
+ 'drain',
455
+ // 'error', // 单独处理,未注册 'error' 事件处理程序,错误将冒泡到全局导致程序崩溃
456
+ 'finish',
457
+ 'information',
458
+ 'pipe',
459
+ // 'response', 由 processResponse 触发
460
+ 'socket',
461
+ 'timeout',
462
+ 'unpipe',
463
+ 'upgrade'
464
+ ];
465
+ const writeEventEmit = Object.create(null);
466
+ for (const ev of writeEvents)writeEventEmit[ev] = /** @param {...any} args */ function(...args) {
467
+ const m = this // 事件回调,this === clientRequest 实例
468
+ ;
469
+ // log('req event', {ev})
470
+ m.redirectReq.emit(ev, ...args) // 内部请求req 事情转发到 Request
471
+ ;
472
+ };
473
+ // stream.Readable,在响应流上转发读流取事件
474
+ // data 单独处理
475
+ const readEvents = [
476
+ 'close',
477
+ 'end',
478
+ 'error',
479
+ 'pause',
480
+ 'readable',
481
+ 'resume'
482
+ ];
483
+ const readEventEmit = Object.create(null);
484
+ for (const ev of readEvents)readEventEmit[ev] = /** @param {...any} args */ function(...args) {
485
+ const m = this // 事件回调,this === clientRequest 实例
486
+ ;
487
+ // log('res event', {ev})
488
+ m.redirectReq.emit(ev, ...args) // 向上触发事件
489
+ ;
490
+ };
491
+ // Error types with codes
492
+ const RedirectionError = utils.createErrorType('ERR_FR_REDIRECTION_FAILURE', 'Redirected request failed');
493
+ const TooManyRedirectsError = utils.createErrorType('ERR_FR_TOO_MANY_REDIRECTS', 'Maximum number of redirects exceeded', RedirectionError);
494
+ const MaxBodyLengthExceededError = utils.createErrorType('ERR_FR_MAX_BODY_LENGTH_EXCEEDED', 'Request body larger than maxBodyLength limit');
495
+ const WriteAfterEndError = utils.createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
496
+ // request err
497
+ const HostNotfoundError = utils.createErrorType('ERR_HOSTNOTFOUND', 'DNS 解析失败,主机名可能无效');
498
+ const ConnRefusedError = utils.createErrorType('ERR_CONNREFUSED', '连接被拒绝,目标服务器可能不可用');
499
+ const ConnTimedoutError = utils.createErrorType('ERR_CONNTIMEDOUT', '请求超时,请检查网络连接或服务器负载');
500
+ const ConnResetError = utils.createErrorType('ERR_CONNRESET', '连接被重置,可能是网络问题或服务器关闭了连接');
501
+ let Request = class Request extends stream$1.Duplex {
660
502
  /**
661
- * React to responses of native requests
662
- * 接管 response 事件,非重定向,触发 response 事件
663
- * @param {Response} res
664
- */
665
- m._onResponse = res => {
666
- try {
667
- m.processResponse(res);
668
- } catch (cause) {
669
- m.emit(
670
- 'error',
671
- cause instanceof RedirectionError ? cause : new RedirectionError({cause: cause})
672
- );
673
- }
674
- };
675
-
676
- // Proxy all other public ClientRequest methods 'getHeader'
677
- for (const method of writeMethods) {
678
- // @ts-ignore
679
- m[method] = (a, b) => {
680
- // log(method, {a, b})
681
- // @ts-ignore
682
- m._currentRequest?.[method](a, b);
683
- };
684
- }
685
-
686
- // Proxy all public ClientRequest properties
687
- // 'aborted', 'connection' 弃用
688
- for (const property of writeProps) {
689
- Object.defineProperty(m, property, {
690
- get() {
691
- // @ts-ignore
692
- const val = m._currentRequest?.[property];
693
- // log('get property', {property})
694
- return val
695
- },
696
- });
697
- }
698
-
699
- // 流模式
700
- if (opts.stream) {
701
- // 被 pipe 作为目标时触发,拷贝 src headers
702
- m.on(
703
- 'pipe',
704
- /** @param {stream.Readable & {headers?: Object.<string, string>}} src */ src => {
705
- // m.ntick &&
706
- if (m._currentRequest) {
707
- m.emit(
708
- 'error',
709
- new Error('You cannot pipe to this stream after the outbound request has started.')
710
- );
711
- }
712
-
713
- m.pipesrc = src;
714
-
715
- if (utils.isReadStream(src)) {
716
- // @ts-ignore
717
- if (!m.hasHeader('content-type')) m.setHeader('content-type', mime.lookup(src.path));
718
- } else {
719
- // 拷贝请求头
720
- if (src.headers) {
721
- for (const k of Object.keys(src.headers)) {
722
- if (!m.hasHeader(k)) {
723
- m.setHeader(k, src.headers[k]);
724
- }
725
- }
726
- }
727
-
728
- // @ts-ignore
729
- if (src.opt.method && !m.opt.method) m.opt.method = src.opt.method;
730
- }
731
- }
732
- );
733
- }
734
-
735
- // Perform the first request
736
- // m.request(); // 创建时不连接,写入数据时连接,否则 pipe 时无法写入header
737
- }
738
-
739
- /**
740
503
  * Executes the next native request (initial or redirect)
741
504
  * @returns http(s) 实例
742
- */
743
- request() {
744
- let R = null;
745
- const m = this;
746
- const {opt} = m;
747
-
748
- try {
749
- // reset read stream
750
- m.response = null;
751
- m.responseStarted = false;
752
- m.responseStream = null;
753
- m.timing = false;
754
- m.responseStartTime = 0;
755
- m._destdata = false;
756
- m._paused = false;
757
- m._respended = false;
758
-
759
- // m.httpModule = httpModules[protocol];
760
-
761
- // Load the native protocol
762
- let {protocol} = opt;
763
- const {agents} = opt;
764
-
765
- // 代理以目的网址协议为准
766
- // If specified, use the agent corresponding to the protocol
767
- // (HTTP and HTTPS use different types of agents)
768
- // agents 优于 agent
769
- if (agents) {
770
- const scheme = protocol.slice(0, -1);
771
- opt.agent = agents[scheme];
772
-
773
- // http 非隧道代理模式,模块以代理主机为准,其他以目的网址为准
774
- // 代理内部会根据代理协议选择 http(s) 发起请求创建连接
775
- if (protocol === 'http:' && agents.http) {
776
- protocol =
777
- agents.http.proxy && !agents.http.tunnel ? agents.http.proxy.protocol : protocol;
778
- }
779
-
780
- // log({scheme, agents, protocol}, 'request')
781
- }
782
-
783
- const httpModule = httpModules[protocol];
784
- if (!httpModule) throw TypeError(`Unsupported protocol: ${protocol}`)
785
-
786
- // log({opt, protocol}, 'request')
787
- // Create the native request and set up its event handlers
788
- // @ts-ignore
789
-
790
- log$1({httpModule, opt}, 'request');
791
- const req = httpModule.request(opt, m._onResponse);
792
- m._currentRequest = req;
793
- // @ts-ignore
794
- req.redirectReq = m;
795
-
796
- // 启动 startTimer
797
- if (m.startTimer) m._currentRequest.once('socket', m.startTimer);
798
-
799
- // set tcp keep alive to prevent drop connection by peer
800
- req.on(
801
- 'socket',
802
- /** @param {*} socket */ socket => {
803
- // default interval of sending ack packet is 1 minute
804
- socket.setKeepAlive(true, 1000 * 60);
805
- }
806
- );
807
-
808
- // 请求error单独处理
809
- // 'error' 事件处理,避免错误将冒泡到全局导致程序崩溃
810
- req.on('error', err => {
811
- destroyRequest(req); // 释放资源
812
- // @ts-ignore
813
- log$1.error({errcode: err?.code}, 'request');
814
- // @ts-ignore
815
- switch (err?.code) {
816
- case 'ENOTFOUND':
817
- m.emit('error', new HostNotfoundError());
818
- break
819
- case 'ECONNREFUSED':
820
- m.emit('error', new ConnRefusedError());
821
- break
822
- case 'ETIMEDOUT':
823
- m.emit('error', new ConnTimedoutError());
824
- break
825
- case 'ECONNRESET':
826
- m.emit('error', new ConnResetError());
827
- break
828
- default:
829
- m.emit('error', utils.createErrorType('ERR_CONNOTHER', `网络错误: ${err.message}`));
830
- }
831
- });
832
-
833
- // 接收req事件,转发 request 上发射,网络关闭事件,触发 error
834
- for (const ev of writeEvents) req.on(ev, writeEventEmit[ev]);
835
-
836
- // RFC7230§5.3.1: When making a request directly to an origin server, […]
837
- // a client MUST send only the absolute path […] as the request-target.
838
- // When making a request to a proxy, […]
839
- // a client MUST send the target URI in absolute-form […].
840
- m._currentUrl = /^\//.test(opt.path) ? url.format(opt) : opt.path;
841
-
842
- // End a redirected request
843
- // (The first request must be ended explicitly with RedirectableRequest#end)
844
- if (m._isRedirect) {
845
- // Write the request entity and end
846
- let i = 0;
847
- const buffers = m._requestBodyBuffers;
848
-
849
- /**
505
+ */ request() {
506
+ let R = null;
507
+ const m = this;
508
+ const { opt } = m;
509
+ try {
510
+ // reset read stream
511
+ m.response = null;
512
+ m.responseStarted = false;
513
+ m.responseStream = null;
514
+ m.timing = false;
515
+ m.responseStartTime = 0;
516
+ m._destdata = false;
517
+ m._paused = false;
518
+ m._respended = false;
519
+ // m.httpModule = httpModules[protocol];
520
+ // Load the native protocol
521
+ let { protocol } = opt;
522
+ const { agents } = opt;
523
+ // 代理以目的网址协议为准
524
+ // If specified, use the agent corresponding to the protocol
525
+ // (HTTP and HTTPS use different types of agents)
526
+ // agents 优于 agent
527
+ if (agents) {
528
+ const scheme = protocol.slice(0, -1);
529
+ opt.agent = agents[scheme];
530
+ // http 非隧道代理模式,模块以代理主机为准,其他以目的网址为准
531
+ // 代理内部会根据代理协议选择 http(s) 发起请求创建连接
532
+ if (protocol === 'http:' && agents.http) {
533
+ protocol = agents.http.proxy && !agents.http.tunnel ? agents.http.proxy.protocol : protocol;
534
+ }
535
+ // log({scheme, agents, protocol}, 'request')
536
+ }
537
+ const httpModule = httpModules[protocol];
538
+ if (!httpModule) throw TypeError(`Unsupported protocol: ${protocol}`);
539
+ // log({opt, protocol}, 'request')
540
+ // Create the native request and set up its event handlers
541
+ // @ts-ignore
542
+ log$1({
543
+ httpModule,
544
+ opt
545
+ }, 'request');
546
+ const req = httpModule.request(opt, m._onResponse);
547
+ m._currentRequest = req;
548
+ // @ts-ignore
549
+ req.redirectReq = m;
550
+ // 启动 startTimer
551
+ if (m.startTimer) m._currentRequest.once('socket', m.startTimer);
552
+ // set tcp keep alive to prevent drop connection by peer
553
+ req.on('socket', /** @param {*} socket */ (socket)=>{
554
+ // default interval of sending ack packet is 1 minute
555
+ socket.setKeepAlive(true, 1000 * 60);
556
+ });
557
+ // 请求error单独处理
558
+ // 'error' 事件处理,避免错误将冒泡到全局导致程序崩溃
559
+ req.on('error', (err)=>{
560
+ destroyRequest(req) // 释放资源
561
+ ;
562
+ // @ts-ignore
563
+ log$1.error({
564
+ errcode: err == null ? void 0 : err.code
565
+ }, 'request');
566
+ // @ts-ignore
567
+ switch(err == null ? void 0 : err.code){
568
+ case 'ENOTFOUND':
569
+ m.emit('error', new HostNotfoundError());
570
+ break;
571
+ case 'ECONNREFUSED':
572
+ m.emit('error', new ConnRefusedError());
573
+ break;
574
+ case 'ETIMEDOUT':
575
+ m.emit('error', new ConnTimedoutError());
576
+ break;
577
+ case 'ECONNRESET':
578
+ m.emit('error', new ConnResetError());
579
+ break;
580
+ default:
581
+ m.emit('error', utils.createErrorType('ERR_CONNOTHER', `网络错误: ${err.message}`));
582
+ }
583
+ });
584
+ // 接收req事件,转发 到 request 上发射,网络关闭事件,触发 error
585
+ for (const ev of writeEvents)req.on(ev, writeEventEmit[ev]);
586
+ // RFC7230§5.3.1: When making a request directly to an origin server, […]
587
+ // a client MUST send only the absolute path […] as the request-target.
588
+ // When making a request to a proxy, […]
589
+ // a client MUST send the target URI in absolute-form […].
590
+ m._currentUrl = /^\//.test(opt.path) ? url.format(opt) : opt.path;
591
+ // End a redirected request
592
+ // (The first request must be ended explicitly with RedirectableRequest#end)
593
+ if (m._isRedirect) {
594
+ // Write the request entity and end
595
+ let i = 0;
596
+ const buffers = m._requestBodyBuffers;
597
+ /**
850
598
  *
851
599
  * @param {*} error
852
- */
853
- function writeNext(error) {
854
- // Only write if this request has not been redirected yet
855
- /* istanbul ignore else */
856
- if (req === m._currentRequest) {
857
- // Report any write errors
858
- /* istanbul ignore if */
859
- if (error) m.emit('error', error);
860
- // Write the next buffer if there are still left
861
- else if (i < buffers.length) {
862
- const buf = buffers[i++];
863
- /* istanbul ignore else */
864
- if (!req.finished) req.write(buf.data, buf.encoding, writeNext);
865
- }
866
- // End the request if `end` has been called on us
867
- else if (m._ended) req.end();
868
- }
869
- }
870
- writeNext();
871
- }
872
-
873
- R = req;
874
- } catch (e) {
875
- log$1.err(e, 'request');
876
- throw e
877
- }
878
-
879
- return R
880
- }
881
-
882
- /**
600
+ */ function writeNext(error) {
601
+ // Only write if this request has not been redirected yet
602
+ /* istanbul ignore else */ if (req === m._currentRequest) {
603
+ // Report any write errors
604
+ /* istanbul ignore if */ if (error) m.emit('error', error);
605
+ else if (i < buffers.length) {
606
+ const buf = buffers[i++];
607
+ /* istanbul ignore else */ if (!req.finished) req.write(buf.data, buf.encoding, writeNext);
608
+ } else if (m._ended) req.end();
609
+ }
610
+ }
611
+ writeNext();
612
+ }
613
+ R = req;
614
+ } catch (e) {
615
+ log$1.err(e, 'request');
616
+ throw e;
617
+ }
618
+ return R;
619
+ }
620
+ /**
883
621
  * 写入错误,释放请求,触发 abort 终止事件
884
- */
885
- abort() {
886
- destroyRequest(this._currentRequest);
887
- this.emit('abort');
888
- }
889
-
890
- /**
622
+ */ abort() {
623
+ destroyRequest(this._currentRequest);
624
+ this.emit('abort');
625
+ }
626
+ /**
891
627
  * 析构
892
628
  * @param {*} error
893
629
  * @returns
894
- */
895
- destroy(error) {
896
- const m = this;
897
- if (!m._ended) m.end();
898
- if (m.response) m.response.destroy();
899
- if (m.responseStream) m.responseStream.destroy();
900
-
901
- // m.clearTimeout();
902
- destroyRequest(m._currentRequest, error);
903
- super.destroy(error);
904
- return this
905
- }
906
-
907
- /**
630
+ */ destroy(error) {
631
+ const m = this;
632
+ if (!m._ended) m.end();
633
+ if (m.response) m.response.destroy();
634
+ if (m.responseStream) m.responseStream.destroy();
635
+ // m.clearTimeout();
636
+ destroyRequest(m._currentRequest, error);
637
+ super.destroy(error);
638
+ return this;
639
+ }
640
+ /**
908
641
  * 发送数据
909
- */
910
- send() {
911
- const m = this;
912
- const {data} = m.opt;
913
- // 发送数据
914
- if (utils.isStream(data)) {
915
-
916
- data.on('end', () => {
917
- });
918
-
919
- data.once(
920
- 'error',
921
- /** @param {*} err */ err => {
922
- // req.destroy(err)
923
- }
924
- );
925
-
926
- data.on('close', () => {
927
- // if (!ended && !errored) {
928
- // throw new WritebBeenAbortedError()
929
- // }
930
- });
931
-
932
- data.pipe(m); // 写入数据流
933
- } else m.end(data);
934
- }
935
-
936
- /**
642
+ */ send() {
643
+ const m = this;
644
+ const { data } = m.opt;
645
+ // 发送数据
646
+ if (utils.isStream(data)) {
647
+ data.on('end', ()=>{
648
+ });
649
+ data.once('error', /** @param {*} err */ (err)=>{
650
+ // req.destroy(err)
651
+ });
652
+ data.on('close', ()=>{
653
+ // if (!ended && !errored) {
654
+ // throw new WritebBeenAbortedError()
655
+ // }
656
+ });
657
+ data.pipe(m) // 写入数据流
658
+ ;
659
+ } else m.end(data);
660
+ }
661
+ /**
937
662
  * Writes buffered data to the current native request
938
663
  * 如 request 不存在,则创建连接,pipe 时可写入 header
939
664
  * @override - 重写父类方法
@@ -941,514 +666,427 @@ class Request extends stream.Duplex {
941
666
  * @param {BufferEncoding | ((error: Error | null) => void)} [encoding] - Encoding for string data, or the callback if no encoding is provided.
942
667
  * @param {(error: Error | null) => void} [cb] - Callback to signal the end of the write operation.
943
668
  * @returns {boolean} True if the write was successful, false otherwise.
944
- */
945
- write(chunk, encoding, cb) {
946
- const m = this;
947
- // log({data: chunk, encoding, cb}, 'write')
948
-
949
- // Writing is not allowed if end has been called
950
- if (m._ending) {
951
- // throw new WriteAfterEndError()
952
- m.emit('error', new WriteAfterEndError());
953
- return
954
- }
955
-
956
- // ! 数据写入时连接,pipe 时可设置 header
957
- if (!m._currentRequest) m.request();
958
-
959
- // Validate input and shift parameters if necessary
960
- if (!utils.isString(chunk) && !utils.isBuffer(chunk))
961
- throw new TypeError('data should be a string, Buffer or Uint8Array')
962
-
963
- if (utils.isFunction(encoding)) {
964
- // @ts-ignore
965
- cb = encoding;
966
- encoding = null;
967
- }
968
-
969
- // Ignore empty buffers, since writing them doesn't invoke the callback
970
- // https://github.com/nodejs/node/issues/22066
971
- if (chunk.length === 0) {
972
- if (cb) cb(null);
973
- return
974
- }
975
-
976
- // Only write when we don't exceed the maximum body length
977
- if (m._requestBodyLength + chunk.length <= m.opt.maxBodyLength) {
978
- m._requestBodyLength += chunk.length;
979
- m._requestBodyBuffers.push({data: chunk, encoding});
980
- // @ts-ignore
981
- m._currentRequest.write(chunk, encoding, cb);
982
- }
983
- // Error when we exceed the maximum body length
984
- else {
985
- m.emit('error', new MaxBodyLengthExceededError());
986
- m.abort();
987
- }
988
- }
989
-
990
- /**
669
+ */ write(chunk, encoding, cb) {
670
+ const m = this;
671
+ // log({data: chunk, encoding, cb}, 'write')
672
+ // Writing is not allowed if end has been called
673
+ if (m._ending) {
674
+ // throw new WriteAfterEndError()
675
+ m.emit('error', new WriteAfterEndError());
676
+ return;
677
+ }
678
+ // ! 数据写入时连接,pipe 时可设置 header
679
+ if (!m._currentRequest) m.request();
680
+ // Validate input and shift parameters if necessary
681
+ if (!utils.isString(chunk) && !utils.isBuffer(chunk)) throw new TypeError('data should be a string, Buffer or Uint8Array');
682
+ if (utils.isFunction(encoding)) {
683
+ // @ts-ignore
684
+ cb = encoding;
685
+ encoding = null;
686
+ }
687
+ // Ignore empty buffers, since writing them doesn't invoke the callback
688
+ // https://github.com/nodejs/node/issues/22066
689
+ if (chunk.length === 0) {
690
+ if (cb) cb(null);
691
+ return;
692
+ }
693
+ // Only write when we don't exceed the maximum body length
694
+ if (m._requestBodyLength + chunk.length <= m.opt.maxBodyLength) {
695
+ m._requestBodyLength += chunk.length;
696
+ m._requestBodyBuffers.push({
697
+ data: chunk,
698
+ encoding
699
+ });
700
+ // @ts-ignore
701
+ m._currentRequest.write(chunk, encoding, cb);
702
+ } else {
703
+ m.emit('error', new MaxBodyLengthExceededError());
704
+ m.abort();
705
+ }
706
+ }
707
+ /**
991
708
  * Ends the current native request
992
709
  * @override - 重写父类方法
993
710
  * @param {*} [chunk] - Optional data to write before ending the stream.
994
711
  * @param {BufferEncoding | (() => void)} [encoding] - Encoding for string data, or the callback if no encoding is provided.
995
712
  * @param {() => void} [cb] - Optional callback to signal completion.
996
713
  * @returns {this} The current stream instance, to allow chaining.
997
- */
998
- end(chunk, encoding, cb) {
999
- const m = this;
1000
-
1001
- // Shift parameters if necessary
1002
- if (utils.isFunction(chunk)) {
1003
- cb = chunk;
1004
- chunk = null;
1005
- encoding = null;
1006
- } else if (utils.isFunction(encoding)) {
1007
- // @ts-ignore
1008
- cb = encoding;
1009
- encoding = null;
1010
- }
1011
-
1012
- // ! 创建实例时不连接,数据写入时发起连接,连接后无法设置 header,因此 pipe 时可设置 header
1013
- if (!m._currentRequest) m.request();
1014
-
1015
- // Write data if needed and end
1016
- if (!chunk) {
1017
- m._ended = true;
1018
- m._ending = true;
1019
- m._currentRequest.end(null, null, cb);
1020
- } else {
1021
- const currentRequest = m._currentRequest;
1022
- m.write(chunk, encoding, () => {
1023
- m._ended = true;
1024
- currentRequest.end(null, null, cb);
1025
- });
1026
-
1027
- m._ending = true;
1028
- }
1029
-
1030
- return m
1031
- }
1032
-
1033
- /**
714
+ */ end(chunk, encoding, cb) {
715
+ const m = this;
716
+ // Shift parameters if necessary
717
+ if (utils.isFunction(chunk)) {
718
+ cb = chunk;
719
+ chunk = null;
720
+ encoding = null;
721
+ } else if (utils.isFunction(encoding)) {
722
+ // @ts-ignore
723
+ cb = encoding;
724
+ encoding = null;
725
+ }
726
+ // ! 创建实例时不连接,数据写入时发起连接,连接后无法设置 header,因此 pipe 时可设置 header
727
+ if (!m._currentRequest) m.request();
728
+ // Write data if needed and end
729
+ if (!chunk) {
730
+ m._ended = true;
731
+ m._ending = true;
732
+ m._currentRequest.end(null, null, cb);
733
+ } else {
734
+ const currentRequest = m._currentRequest;
735
+ m.write(chunk, encoding, ()=>{
736
+ m._ended = true;
737
+ currentRequest.end(null, null, cb);
738
+ });
739
+ m._ending = true;
740
+ }
741
+ return m;
742
+ }
743
+ /**
1034
744
  *
1035
745
  * @param {string} name
1036
746
  * @returns
1037
- */
1038
- hasHeader(name) {
1039
- return Object.keys(this.opt.headers).includes(name)
1040
- }
1041
-
1042
- /**
747
+ */ hasHeader(name) {
748
+ return Object.keys(this.opt.headers).includes(name);
749
+ }
750
+ /**
1043
751
  *
1044
752
  * @param {string} name
1045
753
  * @returns {string}
1046
- */
1047
- getHeader(name) {
1048
- return this.opt.headers[name]
1049
- }
1050
-
1051
- /**
754
+ */ getHeader(name) {
755
+ return this.opt.headers[name];
756
+ }
757
+ /**
1052
758
  * Sets a header value on the current native request
1053
759
  * @param {string} name
1054
760
  * @param {string} value
1055
- */
1056
- setHeader(name, value) {
1057
- this.opt.headers[name] = value;
1058
- this._currentRequest?.setHeader(name, value);
1059
- }
1060
-
1061
- /**
761
+ */ setHeader(name, value) {
762
+ var _this__currentRequest;
763
+ this.opt.headers[name] = value;
764
+ (_this__currentRequest = this._currentRequest) == null ? void 0 : _this__currentRequest.setHeader(name, value);
765
+ }
766
+ /**
1062
767
  * Clears a header value on the current native request
1063
768
  * @param {string} name
1064
- */
1065
- removeHeader(name) {
1066
- delete this.opt.headers[name];
1067
- this._currentRequest?.removeHeader(name);
1068
- }
1069
-
1070
- /**
769
+ */ removeHeader(name) {
770
+ var _this__currentRequest;
771
+ delete this.opt.headers[name];
772
+ (_this__currentRequest = this._currentRequest) == null ? void 0 : _this__currentRequest.removeHeader(name);
773
+ }
774
+ /**
1071
775
  * 标头是否已发送
1072
776
  * @returns
1073
- */
1074
- get headersSent() {
1075
- return this._currentRequest?.headersSent
1076
- }
1077
-
1078
- /**
777
+ */ get headersSent() {
778
+ var _this__currentRequest;
779
+ return (_this__currentRequest = this._currentRequest) == null ? void 0 : _this__currentRequest.headersSent;
780
+ }
781
+ /**
1079
782
  * Global timeout for all underlying requests
1080
783
  * @param {*} msecs
1081
784
  * @param {*} callback
1082
785
  * @returns
1083
- */
1084
- setTimeout(msecs, callback) {
1085
- const m = this;
1086
-
1087
- /**
786
+ */ setTimeout(msecs, callback) {
787
+ const m = this;
788
+ /**
1088
789
  * Destroys the socket on timeout
1089
790
  * @param {*} socket
1090
- */
1091
- function destroyOnTimeout(socket) {
1092
- socket.setTimeout(msecs);
1093
- socket.removeListener('timeout', socket.destroy);
1094
- socket.addListener('timeout', socket.destroy);
1095
- }
1096
-
1097
- /**
791
+ */ function destroyOnTimeout(socket) {
792
+ socket.setTimeout(msecs);
793
+ socket.removeListener('timeout', socket.destroy);
794
+ socket.addListener('timeout', socket.destroy);
795
+ }
796
+ /**
1098
797
  * Sets up a timer to trigger a timeout event
1099
798
  * @param {*} socket
1100
- */
1101
- function startTimer(socket) {
1102
- if (m.startTimer) m.startTimer = null;
1103
-
1104
- if (m._timeout) clearTimeout(m._timeout);
1105
-
1106
- m._timeout = setTimeout(() => {
1107
- m.emit('timeout');
1108
- clearTimer();
1109
- }, msecs);
1110
-
1111
- destroyOnTimeout(socket);
1112
- }
1113
-
1114
- // Stops a timeout from triggering
1115
- function clearTimer() {
1116
- // Clear the timeout
1117
- if (m._timeout) {
1118
- clearTimeout(m._timeout);
1119
- m._timeout = null;
1120
- }
1121
-
1122
- // Clean up all attached listeners
1123
- m.removeListener('abort', clearTimer);
1124
- m.removeListener('error', clearTimer);
1125
- m.removeListener('response', clearTimer);
1126
- m.removeListener('close', clearTimer);
1127
-
1128
- if (callback) {
1129
- m.removeListener('timeout', callback);
1130
- }
1131
- if (!m.socket) {
1132
- m._currentRequest.removeListener('socket', startTimer);
1133
- }
1134
- }
1135
-
1136
- // Attach callback if passed
1137
- if (callback) m.on('timeout', callback);
1138
-
1139
- // Start the timer if or when the socket is opened
1140
- if (m.socket) startTimer(m.socket);
1141
- else m.startTimer = startTimer; // 未连接,先登记,连接后启动
1142
-
1143
- // Clean up on events
1144
- m.on('socket', destroyOnTimeout);
1145
- m.on('abort', clearTimer);
1146
- m.on('error', clearTimer);
1147
- m.on('response', clearTimer);
1148
- m.on('close', clearTimer);
1149
-
1150
- return m
1151
- }
1152
-
1153
- /**
799
+ */ function startTimer(socket) {
800
+ if (m.startTimer) m.startTimer = null;
801
+ if (m._timeout) clearTimeout(m._timeout);
802
+ m._timeout = setTimeout(()=>{
803
+ m.emit('timeout');
804
+ clearTimer();
805
+ }, msecs);
806
+ destroyOnTimeout(socket);
807
+ }
808
+ // Stops a timeout from triggering
809
+ function clearTimer() {
810
+ // Clear the timeout
811
+ if (m._timeout) {
812
+ clearTimeout(m._timeout);
813
+ m._timeout = null;
814
+ }
815
+ // Clean up all attached listeners
816
+ m.removeListener('abort', clearTimer);
817
+ m.removeListener('error', clearTimer);
818
+ m.removeListener('response', clearTimer);
819
+ m.removeListener('close', clearTimer);
820
+ if (callback) {
821
+ m.removeListener('timeout', callback);
822
+ }
823
+ if (!m.socket) {
824
+ m._currentRequest.removeListener('socket', startTimer);
825
+ }
826
+ }
827
+ // Attach callback if passed
828
+ if (callback) m.on('timeout', callback);
829
+ // Start the timer if or when the socket is opened
830
+ if (m.socket) startTimer(m.socket);
831
+ else m.startTimer = startTimer // 未连接,先登记,连接后启动
832
+ ;
833
+ // Clean up on events
834
+ m.on('socket', destroyOnTimeout);
835
+ m.on('abort', clearTimer);
836
+ m.on('error', clearTimer);
837
+ m.on('response', clearTimer);
838
+ m.on('close', clearTimer);
839
+ return m;
840
+ }
841
+ /**
1154
842
  *
1155
843
  * @param {*} options
1156
- */
1157
- sanitizeOptions(options) {
1158
- // Ensure headers are always present
1159
- if (!options.headers) options.headers = {};
1160
-
1161
- // Since http.request treats host as an alias of hostname,
1162
- // but the url module interprets host as hostname plus port,
1163
- // eliminate the host property to avoid confusion.
1164
- if (options.host) {
1165
- // Use hostname if set, because it has precedence
1166
- if (!options.hostname) {
1167
- options.hostname = options.host;
1168
- }
1169
- options.host = undefined;
1170
- }
1171
-
1172
- // Complete the URL object when necessary
1173
- if (!options.pathname && options.path) {
1174
- const searchPos = options.path.indexOf('?');
1175
- if (searchPos < 0) {
1176
- options.pathname = options.path;
1177
- } else {
1178
- options.pathname = options.path.substring(0, searchPos);
1179
- options.search = options.path.substring(searchPos);
1180
- }
1181
- }
1182
- }
1183
-
1184
- /**
844
+ */ sanitizeOptions(options) {
845
+ // Ensure headers are always present
846
+ if (!options.headers) options.headers = {};
847
+ // Since http.request treats host as an alias of hostname,
848
+ // but the url module interprets host as hostname plus port,
849
+ // eliminate the host property to avoid confusion.
850
+ if (options.host) {
851
+ // Use hostname if set, because it has precedence
852
+ if (!options.hostname) {
853
+ options.hostname = options.host;
854
+ }
855
+ options.host = undefined;
856
+ }
857
+ // Complete the URL object when necessary
858
+ if (!options.pathname && options.path) {
859
+ const searchPos = options.path.indexOf('?');
860
+ if (searchPos < 0) {
861
+ options.pathname = options.path;
862
+ } else {
863
+ options.pathname = options.path.substring(0, searchPos);
864
+ options.search = options.path.substring(searchPos);
865
+ }
866
+ }
867
+ }
868
+ /**
1185
869
  * Processes a response from the current native request
1186
870
  * @param {Response} response
1187
871
  * @returns
1188
- */
1189
- processResponse(response) {
1190
- const m = this;
1191
- const {opt} = m;
1192
-
1193
- // Store the redirected response
1194
- const {statusCode} = response;
1195
- if (opt.trackRedirects) {
1196
- m._redirects.push({
1197
- url: m._currentUrl,
1198
- headers: response.headers,
1199
- statusCode,
1200
- });
1201
- }
1202
-
1203
- // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
1204
- // that further action needs to be taken by the user agent in order to
1205
- // fulfill the request. If a Location header field is provided,
1206
- // the user agent MAY automatically redirect its request to the URI
1207
- // referenced by the Location field value,
1208
- // even if the specific status code is not understood.
1209
-
1210
- // If the response is not a redirect; return it as-is
1211
- const {location} = response.headers;
1212
-
1213
- // log({statusCode, headers: response.headers}, 'processResponse')
1214
-
1215
- if (!location || opt.followRedirects === false || statusCode < 300 || statusCode >= 400) {
1216
- // 非重定向,返回给原始回调处理
1217
- response.responseUrl = m._currentUrl;
1218
- response.redirects = m._redirects;
1219
-
1220
- if (opt.stream) m.response = response;
1221
-
1222
- // Be a good stream and emit end when the response is finished.
1223
- // Hack to emit end on close because of a core bug that never fires end
1224
- response.on('close', () => {
1225
- if (!m._respended) {
1226
- response.emit('end');
1227
- }
1228
- });
1229
-
1230
- response.once('end', () => {
1231
- m._respended = true;
1232
- });
1233
-
1234
- const responseStream = m.processStream(response);
1235
- // NOTE: responseStartTime is deprecated in favor of .timings
1236
- response.responseStartTime = m.responseStartTime;
1237
-
1238
- // 触发原回调函数
1239
- m.resCallback?.(response, responseStream);
1240
-
1241
- // 类似 ClientRequest,触发 response 事件
1242
- m.emit('response', response, responseStream);
1243
-
1244
- // Clean up
1245
- m._requestBodyBuffers = [];
1246
- return // 退出,不继续处理
1247
- }
1248
-
1249
- // The response is a redirect, so abort the current request
1250
- destroyRequest(m._currentRequest);
1251
- // Discard the remainder of the response to avoid waiting for data
1252
- response.destroy();
1253
-
1254
- // RFC7231§6.4: A client SHOULD detect and intervene
1255
- // in cyclical redirections (i.e., "infinite" redirection loops).
1256
- if (++m._redirectCount > opt.maxRedirects) throw new TooManyRedirectsError()
1257
-
1258
- // Store the request headers if applicable
1259
- let requestHeaders;
1260
- const {beforeRedirect} = opt;
1261
- if (beforeRedirect) {
1262
- requestHeaders = {
1263
- // The Host header was set by nativeProtocol.request
1264
- // @ts-ignore
1265
- Host: response.req.getHeader('host'),
1266
- ...opt.headers,
1267
- };
1268
- }
1269
-
1270
- // RFC7231§6.4: Automatic redirection needs to done with
1271
- // care for methods not known to be safe, […]
1272
- // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
1273
- // the request method from POST to GET for the subsequent request.
1274
- const {method} = opt;
1275
- if (
1276
- ((statusCode === 301 || statusCode === 302) && opt.method === 'POST') ||
1277
- // RFC7231§6.4.4: The 303 (See Other) status code indicates that
1278
- // the server is redirecting the user agent to a different resource […]
1279
- // A user agent can perform a retrieval request targeting that URI
1280
- // (a GET or HEAD request if using HTTP) […]
1281
- (statusCode === 303 && !/^(?:GET|HEAD)$/.test(opt.method))
1282
- ) {
1283
- m.opt.method = 'GET';
1284
- // Drop a possible entity and headers related to it
1285
- m._requestBodyBuffers = [];
1286
- removeMatchingHeaders(/^content-/i, opt.headers);
1287
- }
1288
-
1289
- // Drop the Host header, as the redirect might lead to a different host
1290
- const currentHostHeader = removeMatchingHeaders(/^host$/i, opt.headers);
1291
-
1292
- // If the redirect is relative, carry over the host of the last request
1293
- const currentUrlParts = utils.parseUrl(m._currentUrl);
1294
- const currentHost = currentHostHeader || currentUrlParts.host;
1295
- const currentUrl = /^\w+:/.test(location)
1296
- ? m._currentUrl
1297
- : url.format(Object.assign(currentUrlParts, {host: currentHost}));
1298
-
1299
- // Create the redirected request
1300
- const redirectUrl = utils.resolveUrl(location, currentUrl);
1301
-
1302
- log$1({redirectUrl}, 'redirecting to');
1303
-
1304
- m._isRedirect = true;
1305
- // 覆盖原 url 解析部分,包括 protocol、hostname、port等
1306
- utils.spreadUrlObject(redirectUrl, m.opt);
1307
-
1308
- // Drop confidential headers when redirecting to a less secure protocol
1309
- // or to a different domain that is not a superdomain
1310
- if (
1311
- (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== 'https:') ||
1312
- (redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost))
1313
- ) {
1314
- removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this.opt.headers);
1315
- }
1316
-
1317
- // Evaluate the beforeRedirect callback
1318
- if (utils.isFunction(beforeRedirect)) {
1319
- const responseDetails = {
1320
- headers: response.headers,
1321
- statusCode,
1322
- };
1323
- const requestDetails = {
1324
- url: currentUrl,
1325
- method,
1326
- headers: requestHeaders,
1327
- };
1328
-
1329
- beforeRedirect(opt, responseDetails, requestDetails);
1330
- m.sanitizeOptions(opt);
1331
- }
1332
-
1333
- // Perform the redirected request
1334
- m.request(); // 重新执行请求
1335
- }
1336
-
1337
- /**
872
+ */ processResponse(response) {
873
+ const m = this;
874
+ const { opt } = m;
875
+ // Store the redirected response
876
+ const { statusCode } = response;
877
+ if (opt.trackRedirects) {
878
+ m._redirects.push({
879
+ url: m._currentUrl,
880
+ headers: response.headers,
881
+ statusCode
882
+ });
883
+ }
884
+ // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
885
+ // that further action needs to be taken by the user agent in order to
886
+ // fulfill the request. If a Location header field is provided,
887
+ // the user agent MAY automatically redirect its request to the URI
888
+ // referenced by the Location field value,
889
+ // even if the specific status code is not understood.
890
+ // If the response is not a redirect; return it as-is
891
+ const { location } = response.headers;
892
+ // log({statusCode, headers: response.headers}, 'processResponse')
893
+ if (!location || opt.followRedirects === false || statusCode < 300 || statusCode >= 400) {
894
+ // 非重定向,返回给原始回调处理
895
+ response.responseUrl = m._currentUrl;
896
+ response.redirects = m._redirects;
897
+ if (opt.stream) m.response = response;
898
+ // Be a good stream and emit end when the response is finished.
899
+ // Hack to emit end on close because of a core bug that never fires end
900
+ response.on('close', ()=>{
901
+ if (!m._respended) {
902
+ response.emit('end');
903
+ }
904
+ });
905
+ response.once('end', ()=>{
906
+ m._respended = true;
907
+ });
908
+ const responseStream = m.processStream(response);
909
+ // NOTE: responseStartTime is deprecated in favor of .timings
910
+ response.responseStartTime = m.responseStartTime;
911
+ // 触发原回调函数
912
+ m.resCallback == null ? void 0 : m.resCallback.call(m, response, responseStream);
913
+ // 类似 ClientRequest,触发 response 事件
914
+ m.emit('response', response, responseStream);
915
+ // Clean up
916
+ m._requestBodyBuffers = [];
917
+ return; // 退出,不继续处理
918
+ }
919
+ // The response is a redirect, so abort the current request
920
+ destroyRequest(m._currentRequest);
921
+ // Discard the remainder of the response to avoid waiting for data
922
+ response.destroy();
923
+ // RFC7231§6.4: A client SHOULD detect and intervene
924
+ // in cyclical redirections (i.e., "infinite" redirection loops).
925
+ if (++m._redirectCount > opt.maxRedirects) throw new TooManyRedirectsError();
926
+ // Store the request headers if applicable
927
+ let requestHeaders;
928
+ const { beforeRedirect } = opt;
929
+ if (beforeRedirect) {
930
+ requestHeaders = {
931
+ // The Host header was set by nativeProtocol.request
932
+ // @ts-ignore
933
+ Host: response.req.getHeader('host'),
934
+ ...opt.headers
935
+ };
936
+ }
937
+ // RFC7231§6.4: Automatic redirection needs to done with
938
+ // care for methods not known to be safe, […]
939
+ // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
940
+ // the request method from POST to GET for the subsequent request.
941
+ const { method } = opt;
942
+ if ((statusCode === 301 || statusCode === 302) && opt.method === 'POST' || // RFC7231§6.4.4: The 303 (See Other) status code indicates that
943
+ // the server is redirecting the user agent to a different resource […]
944
+ // A user agent can perform a retrieval request targeting that URI
945
+ // (a GET or HEAD request if using HTTP) […]
946
+ statusCode === 303 && !/^(?:GET|HEAD)$/.test(opt.method)) {
947
+ m.opt.method = 'GET';
948
+ // Drop a possible entity and headers related to it
949
+ m._requestBodyBuffers = [];
950
+ removeMatchingHeaders(/^content-/i, opt.headers);
951
+ }
952
+ // Drop the Host header, as the redirect might lead to a different host
953
+ const currentHostHeader = removeMatchingHeaders(/^host$/i, opt.headers);
954
+ // If the redirect is relative, carry over the host of the last request
955
+ const currentUrlParts = utils.parseUrl(m._currentUrl);
956
+ const currentHost = currentHostHeader || currentUrlParts.host;
957
+ const currentUrl = /^\w+:/.test(location) ? m._currentUrl : url.format(Object.assign(currentUrlParts, {
958
+ host: currentHost
959
+ }));
960
+ // Create the redirected request
961
+ const redirectUrl = utils.resolveUrl(location, currentUrl);
962
+ log$1({
963
+ redirectUrl
964
+ }, 'redirecting to');
965
+ m._isRedirect = true;
966
+ // 覆盖原 url 解析部分,包括 protocol、hostname、port等
967
+ utils.spreadUrlObject(redirectUrl, m.opt);
968
+ // Drop confidential headers when redirecting to a less secure protocol
969
+ // or to a different domain that is not a superdomain
970
+ if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== 'https:' || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
971
+ removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this.opt.headers);
972
+ }
973
+ // Evaluate the beforeRedirect callback
974
+ if (utils.isFunction(beforeRedirect)) {
975
+ const responseDetails = {
976
+ headers: response.headers,
977
+ statusCode
978
+ };
979
+ const requestDetails = {
980
+ url: currentUrl,
981
+ method,
982
+ headers: requestHeaders
983
+ };
984
+ beforeRedirect(opt, responseDetails, requestDetails);
985
+ m.sanitizeOptions(opt);
986
+ }
987
+ // Perform the redirected request
988
+ m.request() // 重新执行请求
989
+ ;
990
+ }
991
+ /**
1338
992
  * 处理响应stream
1339
993
  * 自动解压,透传流,需设置 decompress = false,避免解压数据
1340
994
  * @param {Response} res
1341
995
  * @returns {Response | stream.Readable}
1342
- */
1343
- processStream(res) {
1344
- const m = this;
1345
- const {opt} = m;
1346
-
1347
- const streams = [res];
1348
- let responseStream = res;
1349
- // 'transfer-encoding': 'chunked'时,无content-length,axios v1.2 不能自动解压
1350
- const responseLength = +res.headers['content-length'];
1351
-
1352
- // log('processStream', {
1353
- // statusCode: res.statusCode,
1354
- // responseLength,
1355
- // headers: res.headers,
1356
- // })
1357
-
1358
- if (opt.transformStream) {
1359
- opt.transformStream.responseLength = responseLength;
1360
- streams.push(opt.transformStream);
1361
- }
1362
-
1363
- const empty = utils.noBody(opt.method, res.statusCode);
1364
- // decompress the response body transparently if required
1365
- if (opt.decompress !== false && res.headers['content-encoding']) {
1366
- // if decompress disabled we should not decompress
1367
- // 压缩内容,加入 解压 stream,自动解压,axios v1.2 存在bug,不能自动解压
1368
- // if no content, but headers still say that it is encoded,
1369
- // remove the header not confuse downstream operations
1370
- // if ((!responseLength || res.statusCode === 204) && res.headers['content-encoding']) {
1371
- if (empty && res.headers['content-encoding']) res.headers['content-encoding'] = undefined;
1372
-
1373
- // 'content-encoding': 'gzip',
1374
- switch ((res.headers['content-encoding'] || '').toLowerCase()) {
1375
- /*eslint default-case:0*/
1376
- case 'gzip':
1377
- case 'x-gzip':
1378
- case 'compress':
1379
- case 'x-compress':
1380
- // add the unzipper to the body stream processing pipeline
1381
- // @ts-ignore
1382
- streams.push(zlib.createUnzip(zlibOptions));
1383
-
1384
- // remove the content-encoding in order to not confuse downstream operations
1385
- res.headers['content-encoding'] = undefined;
1386
- break
1387
-
1388
- case 'deflate':
1389
- // @ts-ignore
1390
- streams.push(new ZlibTransform());
1391
-
1392
- // add the unzipper to the body stream processing pipeline
1393
- // @ts-ignore
1394
- streams.push(zlib.createUnzip(zlibOptions));
1395
-
1396
- // remove the content-encoding in order to not confuse downstream operations
1397
- res.headers['content-encoding'] = undefined;
1398
- break
1399
-
1400
- case 'br':
1401
- if (isBrotliSupported) {
1402
- // @ts-ignore
1403
- streams.push(zlib.createBrotliDecompress(brotliOptions));
1404
- res.headers['content-encoding'] = undefined;
1405
- }
1406
- break
1407
- }
1408
- }
1409
-
1410
- // 响应流,用于读
1411
- // @ts-ignore
1412
- responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
1413
- // 将内部 responseStream 可读流 映射到 redirectReq
1414
-
1415
- // @ts-ignore
1416
- m.responseStream = responseStream;
1417
- // @ts-ignore
1418
- responseStream.redirectReq = m; // 事情触发时引用
1419
-
1420
- // stream 模式,事件透传到 请求类
1421
- if (opt.stream) {
1422
- if (m._paused) responseStream.pause();
1423
- // 写入目的流
1424
- for (const dest of m.pipedests) m.pipeDest(dest);
1425
-
1426
- // 接收responseStream事件,转发 redirectReq 发射
1427
- for (const ev of readEvents) responseStream.on(ev, readEventEmit[ev]);
1428
-
1429
- // @ts-ignore
1430
- responseStream.on('data', chunk => {
1431
- if (m.timing && !m.responseStarted) {
1432
- m.responseStartTime = new Date().getTime();
1433
- }
1434
- m._destdata = true;
1435
- m.emit('data', chunk); // 向上触发
1436
- });
1437
- }
1438
-
1439
- // 可读流结束,触发 finished,方便上层清理
1440
- // A cleanup function which removes all registered listeners.
1441
- const offListeners = stream.finished(responseStream, () => {
1442
- offListeners(); // cleanup
1443
- this.emit('finished');
1444
- });
1445
-
1446
- return responseStream
1447
- }
1448
-
1449
- // Read Stream API
1450
-
1451
- /**
996
+ */ processStream(res) {
997
+ const m = this;
998
+ const { opt } = m;
999
+ const streams = [
1000
+ res
1001
+ ];
1002
+ let responseStream = res;
1003
+ // 'transfer-encoding': 'chunked'时,无content-length,axios v1.2 不能自动解压
1004
+ const responseLength = +res.headers['content-length'];
1005
+ // log('processStream', {
1006
+ // statusCode: res.statusCode,
1007
+ // responseLength,
1008
+ // headers: res.headers,
1009
+ // })
1010
+ if (opt.transformStream) {
1011
+ opt.transformStream.responseLength = responseLength;
1012
+ streams.push(opt.transformStream);
1013
+ }
1014
+ const empty = utils.noBody(opt.method, res.statusCode);
1015
+ // decompress the response body transparently if required
1016
+ if (opt.decompress !== false && res.headers['content-encoding']) {
1017
+ // if decompress disabled we should not decompress
1018
+ // 压缩内容,加入 解压 stream,自动解压,axios v1.2 存在bug,不能自动解压
1019
+ // if no content, but headers still say that it is encoded,
1020
+ // remove the header not confuse downstream operations
1021
+ // if ((!responseLength || res.statusCode === 204) && res.headers['content-encoding']) {
1022
+ if (empty && res.headers['content-encoding']) res.headers['content-encoding'] = undefined;
1023
+ // 'content-encoding': 'gzip',
1024
+ switch((res.headers['content-encoding'] || '').toLowerCase()){
1025
+ /*eslint default-case:0*/ case 'gzip':
1026
+ case 'x-gzip':
1027
+ case 'compress':
1028
+ case 'x-compress':
1029
+ // add the unzipper to the body stream processing pipeline
1030
+ // @ts-ignore
1031
+ streams.push(zlib.createUnzip(zlibOptions));
1032
+ // remove the content-encoding in order to not confuse downstream operations
1033
+ res.headers['content-encoding'] = undefined;
1034
+ break;
1035
+ case 'deflate':
1036
+ // @ts-ignore
1037
+ streams.push(new ZlibTransform());
1038
+ // add the unzipper to the body stream processing pipeline
1039
+ // @ts-ignore
1040
+ streams.push(zlib.createUnzip(zlibOptions));
1041
+ // remove the content-encoding in order to not confuse downstream operations
1042
+ res.headers['content-encoding'] = undefined;
1043
+ break;
1044
+ case 'br':
1045
+ if (isBrotliSupported) {
1046
+ // @ts-ignore
1047
+ streams.push(zlib.createBrotliDecompress(brotliOptions));
1048
+ res.headers['content-encoding'] = undefined;
1049
+ }
1050
+ break;
1051
+ }
1052
+ }
1053
+ // 响应流,用于读
1054
+ // @ts-ignore
1055
+ responseStream = streams.length > 1 ? stream$1.pipeline(streams, utils.noop) : streams[0];
1056
+ // 将内部 responseStream 可读流 映射到 redirectReq
1057
+ // @ts-ignore
1058
+ m.responseStream = responseStream;
1059
+ // @ts-ignore
1060
+ responseStream.redirectReq = m // 事情触发时引用
1061
+ ;
1062
+ // stream 模式,事件透传到 请求类
1063
+ if (opt.stream) {
1064
+ if (m._paused) responseStream.pause();
1065
+ // 写入目的流
1066
+ for (const dest of m.pipedests)m.pipeDest(dest);
1067
+ // 接收responseStream事件,转发 redirectReq 发射
1068
+ for (const ev of readEvents)responseStream.on(ev, readEventEmit[ev]);
1069
+ // @ts-ignore
1070
+ responseStream.on('data', (chunk)=>{
1071
+ if (m.timing && !m.responseStarted) {
1072
+ m.responseStartTime = new Date().getTime();
1073
+ }
1074
+ m._destdata = true;
1075
+ m.emit('data', chunk) // 向上触发
1076
+ ;
1077
+ });
1078
+ }
1079
+ // 可读流结束,触发 finished,方便上层清理
1080
+ // A cleanup function which removes all registered listeners.
1081
+ const offListeners = stream$1.finished(responseStream, ()=>{
1082
+ offListeners() // cleanup
1083
+ ;
1084
+ this.emit('finished');
1085
+ });
1086
+ return responseStream;
1087
+ }
1088
+ // Read Stream API
1089
+ /**
1452
1090
  * 建立读取流管道
1453
1091
  * read stream to write stream
1454
1092
  * pipe 只是建立连接管道,后续自动传输数据
@@ -1458,192 +1096,248 @@ class Request extends stream.Duplex {
1458
1096
  * @param {Object} [opt] - Optional configuration object.
1459
1097
  * @param {boolean} [opt.end=true] - Whether to end the writable stream when the readable stream ends.
1460
1098
  * @returns {T} The destination stream.
1461
- */
1462
- pipe(dest, opts = {}) {
1463
- const m = this;
1464
- // m.pipe()
1465
- // 请求已响应
1466
- if (m.responseStream) {
1467
- // 已有数据,不可pipe
1468
- if (m._destdata)
1469
- m.emit('error', new Error('You cannot pipe after data has been emitted from the response.'));
1470
- else if (m._respended)
1471
- m.emit('error', new Error('You cannot pipe after the response has been ended.'));
1472
- else {
1473
- // stream.Stream.prototype.pipe.call(self, dest, opts);
1474
- super.pipe(dest, opts); // 建立连接管道,自动传输数据
1475
- m.pipeDest(dest);
1476
- return dest // 返回写入 stream
1477
- }
1478
- } else {
1479
- // 已请求还未响应
1480
- m.pipedests.push(dest);
1481
- // stream.Stream.prototype.pipe.call(self, dest, opts);
1482
- super.pipe(dest, opts); // 建立连接管道
1483
- return dest // 返回写入 stream
1484
- }
1485
- }
1486
-
1487
- /**
1099
+ */ pipe(dest, opts = {}) {
1100
+ const m = this;
1101
+ // m.pipe()
1102
+ // 请求已响应
1103
+ if (m.responseStream) {
1104
+ // 已有数据,不可pipe
1105
+ if (m._destdata) m.emit('error', new Error('You cannot pipe after data has been emitted from the response.'));
1106
+ else if (m._respended) m.emit('error', new Error('You cannot pipe after the response has been ended.'));
1107
+ else {
1108
+ // stream.Stream.prototype.pipe.call(self, dest, opts);
1109
+ super.pipe(dest, opts) // 建立连接管道,自动传输数据
1110
+ ;
1111
+ m.pipeDest(dest);
1112
+ return dest // 返回写入 stream
1113
+ ;
1114
+ }
1115
+ } else {
1116
+ // 已请求还未响应
1117
+ m.pipedests.push(dest);
1118
+ // stream.Stream.prototype.pipe.call(self, dest, opts);
1119
+ super.pipe(dest, opts) // 建立连接管道
1120
+ ;
1121
+ return dest // 返回写入 stream
1122
+ ;
1123
+ }
1124
+ }
1125
+ /**
1488
1126
  * 分离先前使用pipe()方法附加的Writable流。
1489
1127
  * @param {stream.Writable} dest
1490
1128
  * @returns
1491
- */
1492
- unpipe(dest) {
1493
- const m = this;
1494
-
1495
- // 请求已响应
1496
- if (m.responseStream) {
1497
- // 已有数据,不可 unpipe
1498
- if (m._destdata)
1499
- m.emit(
1500
- 'error',
1501
- new Error('You cannot unpipe after data has been emitted from the response.')
1502
- );
1503
- else if (m._respended)
1504
- m.emit('error', new Error('You cannot unpipe after the response has been ended.'));
1505
- else {
1506
- // stream.Stream.prototype.pipe.call(self, dest, opts);
1507
- super.unpipe(dest); // 建立连接管道,自动传输数据
1508
- m.pipedests = m.pipedests.filter(v => v !== dest);
1509
- return m
1510
- }
1511
- } else {
1512
- // 已请求还未响应
1513
- m.pipedests = m.pipedests.filter(v => v !== dest);
1514
- super.unpipe(dest); // 从连接管道中分离
1515
- return m
1516
- }
1517
- }
1518
-
1519
- /**
1129
+ */ unpipe(dest) {
1130
+ const m = this;
1131
+ // 请求已响应
1132
+ if (m.responseStream) {
1133
+ // 已有数据,不可 unpipe
1134
+ if (m._destdata) m.emit('error', new Error('You cannot unpipe after data has been emitted from the response.'));
1135
+ else if (m._respended) m.emit('error', new Error('You cannot unpipe after the response has been ended.'));
1136
+ else {
1137
+ // stream.Stream.prototype.pipe.call(self, dest, opts);
1138
+ super.unpipe(dest) // 建立连接管道,自动传输数据
1139
+ ;
1140
+ m.pipedests = m.pipedests.filter((v)=>v !== dest);
1141
+ return m;
1142
+ }
1143
+ } else {
1144
+ // 已请求还未响应
1145
+ m.pipedests = m.pipedests.filter((v)=>v !== dest);
1146
+ super.unpipe(dest) // 从连接管道中分离
1147
+ ;
1148
+ return m;
1149
+ }
1150
+ }
1151
+ /**
1520
1152
  * 收请求响应,传输数据到可写流之前,设置可写流 header
1521
1153
  * content-type 和 content-length,实现数据 透传,比如图片
1522
1154
  * 流模式透传,需设置 decompress = false,避免解压数据
1523
1155
  * (await req.stream('http://google.com/img.png')).pipe(await req.stream('http://mysite.com/img.png'))
1524
1156
  * pipe to dest
1525
1157
  * @param {*} dest
1526
- */
1527
- pipeDest(dest) {
1528
- const m = this;
1529
- const {response} = m;
1530
-
1531
- // Called after the response is received
1532
- if (response?.headers && dest.headers && !dest.headersSent) {
1533
- const caseless = new Caseless(response.headers);
1534
- if (caseless.has('content-type')) {
1535
- const ctname = /** @type {string} */ (caseless.has('content-type'));
1536
- if (dest.setHeader) {
1537
- dest.setHeader(ctname, response.headers[ctname]);
1538
- } else {
1539
- dest.headers[ctname] = response.headers[ctname];
1540
- }
1541
- }
1542
-
1543
- if (caseless.has('content-length')) {
1544
- const clname = /** @type {string} */ (caseless.has('content-length'));
1545
- if (dest.setHeader) {
1546
- dest.setHeader(clname, response.headers[clname]);
1547
- } else {
1548
- dest.headers[clname] = response.headers[clname];
1549
- }
1550
- }
1551
- }
1552
-
1553
- if (response?.headers && dest.setHeader && !dest.headersSent) {
1554
- for (const k of Object.keys(response.headers)) dest.setHeader(k, response.headers[k]);
1555
-
1556
- dest.statusCode = response.statusCode;
1557
- }
1558
-
1559
- if (m.pipefilter) m.pipefilter(response, dest);
1560
- }
1561
-
1562
- /**
1158
+ */ pipeDest(dest) {
1159
+ const m = this;
1160
+ const { response } = m;
1161
+ // Called after the response is received
1162
+ if ((response == null ? void 0 : response.headers) && dest.headers && !dest.headersSent) {
1163
+ const caseless = new Caseless(response.headers);
1164
+ if (caseless.has('content-type')) {
1165
+ const ctname = /** @type {string} */ caseless.has('content-type');
1166
+ if (dest.setHeader) {
1167
+ dest.setHeader(ctname, response.headers[ctname]);
1168
+ } else {
1169
+ dest.headers[ctname] = response.headers[ctname];
1170
+ }
1171
+ }
1172
+ if (caseless.has('content-length')) {
1173
+ const clname = /** @type {string} */ caseless.has('content-length');
1174
+ if (dest.setHeader) {
1175
+ dest.setHeader(clname, response.headers[clname]);
1176
+ } else {
1177
+ dest.headers[clname] = response.headers[clname];
1178
+ }
1179
+ }
1180
+ }
1181
+ if ((response == null ? void 0 : response.headers) && dest.setHeader && !dest.headersSent) {
1182
+ for (const k of Object.keys(response.headers))dest.setHeader(k, response.headers[k]);
1183
+ dest.statusCode = response.statusCode;
1184
+ }
1185
+ if (m.pipefilter) m.pipefilter(response, dest);
1186
+ }
1187
+ /**
1563
1188
  * 暂停read流
1564
- */
1565
- pause() {
1566
- const m = this;
1567
- // 没有流
1568
- if (!m.responseStream) m._paused = true;
1569
- else m.responseStream.pause();
1570
- return m
1571
- }
1572
-
1573
- /**
1189
+ */ pause() {
1190
+ const m = this;
1191
+ // 没有流
1192
+ if (!m.responseStream) m._paused = true;
1193
+ else m.responseStream.pause();
1194
+ return m;
1195
+ }
1196
+ /**
1574
1197
  * 继续read响应流
1575
- */
1576
- resume() {
1577
- const m = this;
1578
- if (!m.responseStream) m._paused = false;
1579
- else m.responseStream.resume();
1580
- return m
1581
- }
1582
-
1583
- isPaused() {
1584
- return this._paused
1585
- }
1586
- }
1587
-
1198
+ */ resume() {
1199
+ const m = this;
1200
+ if (!m.responseStream) m._paused = false;
1201
+ else m.responseStream.resume();
1202
+ return m;
1203
+ }
1204
+ isPaused() {
1205
+ return this._paused;
1206
+ }
1207
+ /**
1208
+ * responseCallback 原消息处理回调
1209
+ * @param {Opts} opts
1210
+ * @param {*} resCallback
1211
+ */ constructor(opts, resCallback){
1212
+ super(), /** @type {NodeJS.Timeout} */ this._timeout = null, /** @type {*} */ this.socket = null, /** @type {http.ClientRequest} */ this._currentRequest = null, /** @type {Response} */ this.response = null, /** @type {stream.Readable} */ this.responseStream = null, this.timing = false, this.responseStarted = false, this.responseStartTime = 0, this._destdata = false, this._paused = false, this._respended = false, /** @type {stream.Readable} */ this.pipesrc = null // 被 pipe 时的 src stream
1213
+ , /** @type {stream.Writable[]} */ this.pipedests = [] // pipe dest
1214
+ , /** @type {*} */ this.startTimer = null;
1215
+ const m = this;
1216
+ // log({opts}, 'new Request')
1217
+ // Initialize the request
1218
+ m.sanitizeOptions(opts);
1219
+ m.opt = opts;
1220
+ m.headers = opts.headers;
1221
+ // log({opts}, 'constructor')
1222
+ m._ended = false;
1223
+ m._ending = false;
1224
+ m._redirectCount = 0;
1225
+ /** @type {any[]} */ m._redirects = [];
1226
+ m._requestBodyLength = 0;
1227
+ /** @type {any[]} */ m._requestBodyBuffers = [];
1228
+ // save the callback if passed
1229
+ m.resCallback = resCallback;
1230
+ /**
1231
+ * React to responses of native requests
1232
+ * 接管 response 事件,非重定向,触发 response 事件
1233
+ * @param {Response} res
1234
+ */ m._onResponse = (res)=>{
1235
+ try {
1236
+ m.processResponse(res);
1237
+ } catch (cause) {
1238
+ m.emit('error', cause instanceof RedirectionError ? cause : new RedirectionError({
1239
+ cause: cause
1240
+ }));
1241
+ }
1242
+ };
1243
+ // Proxy all other public ClientRequest methods 'getHeader'
1244
+ for (const method of writeMethods){
1245
+ // @ts-ignore
1246
+ m[method] = (a, b)=>{
1247
+ var // log(method, {a, b})
1248
+ // @ts-ignore
1249
+ _m__currentRequest;
1250
+ (_m__currentRequest = m._currentRequest) == null ? void 0 : _m__currentRequest[method](a, b);
1251
+ };
1252
+ }
1253
+ // Proxy all public ClientRequest properties
1254
+ // 'aborted', 'connection' 弃用
1255
+ for (const property of writeProps){
1256
+ Object.defineProperty(m, property, {
1257
+ get () {
1258
+ var _m__currentRequest;
1259
+ // @ts-ignore
1260
+ const val = (_m__currentRequest = m._currentRequest) == null ? void 0 : _m__currentRequest[property];
1261
+ // log('get property', {property})
1262
+ return val;
1263
+ }
1264
+ });
1265
+ }
1266
+ // 流模式
1267
+ if (opts.stream) {
1268
+ // 被 pipe 作为目标时触发,拷贝 src headers
1269
+ m.on('pipe', /** @param {stream.Readable & {headers?: Object.<string, string>}} src */ (src)=>{
1270
+ // m.ntick &&
1271
+ if (m._currentRequest) {
1272
+ m.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'));
1273
+ }
1274
+ m.pipesrc = src;
1275
+ if (utils.isReadStream(src)) {
1276
+ // @ts-ignore
1277
+ if (!m.hasHeader('content-type')) m.setHeader('content-type', mime.lookup(src.path));
1278
+ } else {
1279
+ // 拷贝请求头
1280
+ if (src.headers) {
1281
+ for (const k of Object.keys(src.headers)){
1282
+ if (!m.hasHeader(k)) {
1283
+ m.setHeader(k, src.headers[k]);
1284
+ }
1285
+ }
1286
+ }
1287
+ // @ts-ignore
1288
+ if (src.opt.method && !m.opt.method) m.opt.method = src.opt.method;
1289
+ }
1290
+ });
1291
+ }
1292
+ // Perform the first request
1293
+ // m.request(); // 创建时不连接,写入数据时连接,否则 pipe 时无法写入header
1294
+ }
1295
+ };
1588
1296
  /**
1589
1297
  * 释放请求,触发error事件
1590
1298
  * 'error' event, and emit a 'close' event.
1591
1299
  * Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.
1592
1300
  * @param {*} request
1593
1301
  * @param {*} error
1594
- */
1595
- function destroyRequest(request, error) {
1596
- for (const ev of writeEvents) {
1597
- request.removeListener(ev, writeEventEmit[ev]);
1598
- }
1599
- request.on('error', utils.noop);
1600
- request.destroy(error); // 触发 error 事件
1601
- }
1602
-
1302
+ */ function destroyRequest(request, error) {
1303
+ for (const ev of writeEvents){
1304
+ request.removeListener(ev, writeEventEmit[ev]);
1305
+ }
1306
+ request.on('error', utils.noop);
1307
+ request.destroy(error) // 触发 error 事件
1308
+ ;
1309
+ }
1603
1310
  /**
1604
1311
  *
1605
1312
  * @param {RegExp} regex
1606
1313
  * @param {Object.<string, string>} headers
1607
1314
  * @returns
1608
- */
1609
- function removeMatchingHeaders(regex, headers) {
1610
- let lastValue;
1611
- for (const k of Object.keys(headers)) {
1612
- if (regex.test(k)) {
1613
- lastValue = headers[k];
1614
- delete headers[k];
1615
- }
1616
- }
1617
-
1618
- return lastValue === null || typeof lastValue === 'undefined'
1619
- ? undefined
1620
- : String(lastValue).trim()
1621
- }
1622
-
1315
+ */ function removeMatchingHeaders(regex, headers) {
1316
+ let lastValue;
1317
+ for (const k of Object.keys(headers)){
1318
+ if (regex.test(k)) {
1319
+ lastValue = headers[k];
1320
+ delete headers[k];
1321
+ }
1322
+ }
1323
+ return lastValue === null || typeof lastValue === 'undefined' ? undefined : String(lastValue).trim();
1324
+ }
1623
1325
  /**
1624
1326
  *
1625
1327
  * @param {string} subdomain
1626
1328
  * @param {string} domain
1627
1329
  * @returns
1628
- */
1629
- function isSubdomain(subdomain, domain) {
1630
- assert(utils.isString(subdomain) && utils.isString(domain));
1631
- const dot = subdomain.length - domain.length - 1;
1632
- return dot > 0 && subdomain[dot] === '.' && subdomain.endsWith(domain)
1330
+ */ function isSubdomain(subdomain, domain) {
1331
+ assert(utils.isString(subdomain) && utils.isString(domain));
1332
+ const dot = subdomain.length - domain.length - 1;
1333
+ return dot > 0 && subdomain[dot] === '.' && subdomain.endsWith(domain);
1633
1334
  }
1634
1335
 
1635
- /**
1636
- * from 'https://github.com/follow-redirects/follow-redirects'
1637
- * used by axios
1638
- * 修改以支持http、https 代理服务器
1639
- * 代理模式下,http or https 请求,取决于 proxy 代理服务器,而不是目的服务器。
1640
- */
1641
-
1642
- const log = log$2.log({env: `wia:req:${log$2.name((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('request.cjs', document.baseURI).href)))}`}); // __filename
1643
-
1644
- /** @typedef { import('./request').Response} Response */
1645
-
1646
- /**
1336
+ const log = log$2.log({
1337
+ env: `wia:req:${log$2.name((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('request.cjs', document.baseURI).href)))}`
1338
+ }) // __filename
1339
+ ;
1340
+ /** @typedef { import('./request').Response} Response */ /**
1647
1341
  * @typedef {object} Opts
1648
1342
  * @prop {Object.<string,string>} [headers]
1649
1343
  * @prop {string} [url]
@@ -1665,104 +1359,89 @@ const log = log$2.log({env: `wia:req:${log$2.name((typeof document === 'undefine
1665
1359
  * @prop {number} [maxRedirects=21] - 最大重定向次数
1666
1360
  * @prop {number} [maxBodyLength = 0] - body限制,缺省不限
1667
1361
  * @prop {*} [trackRedirects]
1668
- */
1669
-
1670
- /** @typedef {(res: Response, stream?: stream.Readable) => void} Cb*/
1671
-
1672
- utils.createErrorType(
1673
- 'ERR_STREAM_WRITE_BEEN_ABORTED',
1674
- 'Request stream has been aborted'
1675
- )
1676
-
1677
- // Preventive platform detection
1678
- // istanbul ignore
1679
- ;(function detectUnsupportedEnvironment() {
1680
- const looksLikeNode = typeof process !== 'undefined';
1681
- const looksLikeBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
1682
- const looksLikeV8 = utils.isFunction(Error.captureStackTrace);
1683
- if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
1684
- log.warn('The follow-redirects package should be excluded from browser builds.');
1685
- }
1686
- })();
1687
-
1362
+ */ /** @typedef {(res: Response, stream?: stream.Readable) => void} Cb*/ utils.createErrorType('ERR_STREAM_WRITE_BEEN_ABORTED', 'Request stream has been aborted');
1363
+ (function detectUnsupportedEnvironment() {
1364
+ const looksLikeNode = typeof process !== 'undefined';
1365
+ const looksLikeBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
1366
+ const looksLikeV8 = utils.isFunction(Error.captureStackTrace);
1367
+ if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
1368
+ log.warn('The follow-redirects package should be excluded from browser builds.');
1369
+ }
1370
+ })();
1688
1371
  /**
1689
1372
  * 封装http(s),实现重定向
1690
1373
  * 重定向可能切换http、https
1691
1374
  * 支持隧道及非隧道、http(s)代理
1692
- */
1693
-
1694
- /**
1375
+ */ /**
1695
1376
  * 初始化参数
1696
1377
  * @param {string | Opts} uri/opts
1697
1378
  * @param {Opts | Cb} [opts] /cb
1698
1379
  * @param {Cb} [cb]
1699
1380
  * @returns {{opt: Opts, cb: Cb}}
1700
- */
1701
- function init(uri, opts, cb) {
1702
- let R;
1703
- try {
1704
- // Parse parameters, ensuring that input is an object
1705
- if (utils.isURL(uri)) uri = utils.spreadUrlObject(uri);
1706
- else if (utils.isString(uri)) uri = utils.spreadUrlObject(utils.parseUrl(uri));
1707
- else {
1708
- // @ts-ignore
1709
- cb = opts;
1710
- // @ts-ignore
1711
- opts = uri;
1712
- // @ts-ignore
1713
- const {url} = opts;
1714
- // url,解析
1715
- if (url) {
1716
- // @ts-ignore
1717
- // biome-ignore lint/performance/noDelete: <explanation>
1718
- delete opts.url;
1719
- if (utils.isURL(url)) uri = utils.spreadUrlObject(url);
1720
- else if (utils.isString(url)) uri = utils.spreadUrlObject(utils.parseUrl(url));
1721
- } else {
1722
- // @ts-ignore
1723
- opts = uri; // 不判断 utils.validateUrl(uri)
1724
- uri = {};
1725
- }
1726
- }
1727
-
1728
- if (utils.isFunction(opts)) {
1729
- // @ts-ignore
1730
- cb = opts;
1731
- opts = {};
1732
- }
1733
-
1734
- // copy options
1735
- /** @type {Opts} */
1736
- const opt = {
1737
- // @ts-ignore
1738
- ...uri,
1739
- ...opts,
1740
- };
1741
-
1742
- if (!utils.isString(opt.host) && !utils.isString(opt.hostname)) opt.hostname = '::1';
1743
- opt.method = (opt.method ?? 'get').toUpperCase();
1744
-
1745
- // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
1746
- opt.maxBodyLength = opt.maxBodyLength ?? Number.POSITIVE_INFINITY;
1747
- opt.maxRedirects = opt.maxRedirects ?? 21;
1748
- if (opt.maxRedirects === 0) opt.followRedirects = false;
1749
- opt.headers = opt.headers ?? {
1750
- Accept: 'application/json, text/plain, */*',
1751
- 'User-Agent':
1752
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
1753
- 'Accept-Encoding': 'gzip, compress, deflate, br',
1754
- };
1755
-
1756
- R = {opt, cb};
1757
- // log({R}, 'init')
1758
- } catch (e) {
1759
- log.err(e, 'init');
1760
- }
1761
-
1762
- // @ts-ignore
1763
- return R
1764
- }
1765
-
1381
+ */ function init(uri, opts, cb) {
1382
+ let R;
1383
+ try {
1384
+ // Parse parameters, ensuring that input is an object
1385
+ if (utils.isURL(uri)) uri = utils.spreadUrlObject(uri);
1386
+ else if (utils.isString(uri)) uri = utils.spreadUrlObject(utils.parseUrl(uri));
1387
+ else {
1388
+ // @ts-ignore
1389
+ cb = opts;
1390
+ // @ts-ignore
1391
+ opts = uri;
1392
+ // @ts-ignore
1393
+ const { url } = opts;
1394
+ // url,解析
1395
+ if (url) {
1396
+ // @ts-ignore
1397
+ // biome-ignore lint/performance/noDelete: <explanation>
1398
+ delete opts.url;
1399
+ if (utils.isURL(url)) uri = utils.spreadUrlObject(url);
1400
+ else if (utils.isString(url)) uri = utils.spreadUrlObject(utils.parseUrl(url));
1401
+ } else {
1402
+ // @ts-ignore
1403
+ opts = uri // 不判断 utils.validateUrl(uri)
1404
+ ;
1405
+ uri = {};
1406
+ }
1407
+ }
1408
+ if (utils.isFunction(opts)) {
1409
+ // @ts-ignore
1410
+ cb = opts;
1411
+ opts = {};
1412
+ }
1413
+ // copy options
1414
+ /** @type {Opts} */ const opt = {
1415
+ // @ts-ignore
1416
+ ...uri,
1417
+ ...opts
1418
+ };
1419
+ if (!utils.isString(opt.host) && !utils.isString(opt.hostname)) opt.hostname = '::1';
1420
+ var _opt_method;
1421
+ opt.method = ((_opt_method = opt.method) != null ? _opt_method : 'get').toUpperCase();
1422
+ var _opt_maxBodyLength;
1423
+ // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
1424
+ opt.maxBodyLength = (_opt_maxBodyLength = opt.maxBodyLength) != null ? _opt_maxBodyLength : Number.POSITIVE_INFINITY;
1425
+ var _opt_maxRedirects;
1426
+ opt.maxRedirects = (_opt_maxRedirects = opt.maxRedirects) != null ? _opt_maxRedirects : 21;
1427
+ if (opt.maxRedirects === 0) opt.followRedirects = false;
1428
+ var _opt_headers;
1429
+ opt.headers = (_opt_headers = opt.headers) != null ? _opt_headers : {
1430
+ Accept: 'application/json, text/plain, */*',
1431
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
1432
+ 'Accept-Encoding': 'gzip, compress, deflate, br'
1433
+ };
1434
+ R = {
1435
+ opt,
1436
+ cb
1437
+ };
1438
+ // log({R}, 'init')
1439
+ } catch (e) {
1440
+ log.err(e, 'init');
1441
+ }
1442
+ // @ts-ignore
1443
+ return R;
1444
+ }
1766
1445
  /**
1767
1446
  * Executes a request, following redirects
1768
1447
  * 替换原 http(s).request,参数类似
@@ -1774,64 +1453,51 @@ function init(uri, opts, cb) {
1774
1453
  * @param {Opts | Cb} [opts] /callback
1775
1454
  * @param {Cb} [callback] /null
1776
1455
  * @returns {Request}
1777
- */
1778
- function request(uri, opts, callback) {
1779
- let R = null;
1780
-
1781
- try {
1782
- // @ts-ignore
1783
- const {opt, cb} = init(uri, opts, callback);
1784
- // log({uri, opt, opts}, 'request')
1785
-
1786
- const {data, stream} = opt;
1787
- // data 在本函数完成处理,不传递到 request
1788
- opt.data = undefined;
1789
-
1790
- // @ts-ignore
1791
- const req = new Request(opt, cb);
1792
-
1793
- // 非流模式,自动发送请求,流模式通过流写入发送
1794
- if (!stream) {
1795
- // 发送数据
1796
- if (utils.isStream(data)) {
1797
- // Send the request
1798
- let ended = false;
1799
- let errored = false;
1800
-
1801
- data.on('end', () => {
1802
- ended = true;
1803
- });
1804
-
1805
- data.once(
1806
- 'error',
1807
- /** @param {*} err */ err => {
1808
- errored = true;
1809
- // req.destroy(err)
1810
- }
1811
- );
1812
-
1813
- data.on('close', () => {
1814
- if (!ended && !errored) {
1815
- // throw new WritebBeenAbortedError()
1816
- }
1817
- });
1818
-
1819
- // log.error({data}, 'request data.pipe')
1820
- data.pipe(req); // 写入数据流
1821
- } else {
1822
- // log.error({data}, 'request req.end')
1823
- req.end(data); // 写入数据
1824
- }
1825
- }
1826
-
1827
- R = req;
1828
- } catch (e) {
1829
- log.err(e, 'request');
1830
- }
1831
-
1832
- return R
1833
- }
1834
-
1456
+ */ function request(uri, opts, callback) {
1457
+ let R = null;
1458
+ try {
1459
+ // @ts-ignore
1460
+ const { opt, cb } = init(uri, opts, callback);
1461
+ // log({uri, opt, opts}, 'request')
1462
+ const { data, stream } = opt;
1463
+ // data 在本函数完成处理,不传递到 request
1464
+ opt.data = undefined;
1465
+ // @ts-ignore
1466
+ const req = new Request(opt, cb);
1467
+ // 非流模式,自动发送请求,流模式通过流写入发送
1468
+ if (!stream) {
1469
+ // 发送数据
1470
+ if (utils.isStream(data)) {
1471
+ // Send the request
1472
+ let ended = false;
1473
+ let errored = false;
1474
+ data.on('end', ()=>{
1475
+ ended = true;
1476
+ });
1477
+ data.once('error', /** @param {*} err */ (err)=>{
1478
+ errored = true;
1479
+ // req.destroy(err)
1480
+ });
1481
+ data.on('close', ()=>{
1482
+ if (!ended && !errored) {
1483
+ // throw new WritebBeenAbortedError()
1484
+ }
1485
+ });
1486
+ // log.error({data}, 'request data.pipe')
1487
+ data.pipe(req) // 写入数据流
1488
+ ;
1489
+ } else {
1490
+ // log.error({data}, 'request req.end')
1491
+ req.end(data) // 写入数据
1492
+ ;
1493
+ }
1494
+ }
1495
+ R = req;
1496
+ } catch (e) {
1497
+ log.err(e, 'request');
1498
+ }
1499
+ return R;
1500
+ }
1835
1501
  /**
1836
1502
  * 执行简单的数据(支持stream)请求
1837
1503
  * 非流模式,直接写入数据流,流模式,由管道触发,或手动调用 end() data.pipe 写入数据
@@ -1839,32 +1505,29 @@ function request(uri, opts, callback) {
1839
1505
  * organize params for patch, post, put, head, del
1840
1506
  * @param {string} verb
1841
1507
  * @returns {(url: string | Opts, opts?: Opts | Cb, cb?: Cb) => void}}
1842
- */
1843
- function fn(verb) {
1844
- const method = verb.toUpperCase();
1845
- /**
1508
+ */ function fn(verb) {
1509
+ const method = verb.toUpperCase();
1510
+ /**
1846
1511
  *
1847
1512
  * @param {string | Opts} uri /options
1848
1513
  * @param {Opts | Cb} [opts] /callback
1849
1514
  * @param {Cb} [cb] /null
1850
1515
  * @returns
1851
- */
1852
- function fn(uri, opts, cb) {
1853
- // @ts-ignore
1854
- opts.method = method;
1855
- return request(uri, opts, cb)
1856
- }
1857
- return fn
1858
- }
1859
-
1860
- // define like this to please codeintel/intellisense IDEs
1861
- request.get = fn('get');
1862
- request.head = fn('head');
1863
- request.options = fn('options');
1864
- request.post = fn('post');
1865
- request.put = fn('put');
1866
- request.patch = fn('patch');
1867
- request.del = fn('delete');
1516
+ */ function fn(uri, opts, cb) {
1517
+ // @ts-ignore
1518
+ opts.method = method;
1519
+ return request(uri, opts, cb);
1520
+ }
1521
+ return fn;
1522
+ }
1523
+ // define like this to please codeintel/intellisense IDEs
1524
+ request.get = fn('get');
1525
+ request.head = fn('head');
1526
+ request.options = fn('options');
1527
+ request.post = fn('post');
1528
+ request.put = fn('put');
1529
+ request.patch = fn('patch');
1530
+ request.del = fn('delete');
1868
1531
  request.delete = fn('delete');
1869
1532
 
1870
1533
  module.exports = request;