@e-mc/request 0.5.4 → 0.6.1

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/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright 2023 Mile Square Park
1
+ Copyright 2023 Studio Trigger
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @e-mc/request
2
2
 
3
- PEP 402 - Forever
3
+ PEP 402 - Forever Ryuko
4
4
 
5
5
  ## LICENSE
6
6
 
@@ -107,7 +107,7 @@ class HttpHost {
107
107
  });
108
108
  socket
109
109
  .setNoDelay(false)
110
- .setTimeout(5000)
110
+ .setTimeout(10000)
111
111
  .on('timeout', () => {
112
112
  if (this._tlsConnect) {
113
113
  if (this.error(version) >= 10) {
@@ -173,10 +173,11 @@ class HttpHost {
173
173
  }
174
174
  return false;
175
175
  };
176
- const pattern = new RegExp(`h${i + 1}="([^:]*):(\\d+)"([^,]*)`, 'g');
176
+ const pattern = new RegExp(`h${i + 1}(?:-\\d+)?="([^:]*):(\\d+)"([^,]*)`, 'g');
177
177
  const addresses = [];
178
178
  const time = Date.now();
179
179
  const hostname = this[kHostname];
180
+ const excluded = this[kAltSvcError];
180
181
  let match;
181
182
  while (match = pattern.exec(altSvc)) {
182
183
  const port = match[2];
@@ -187,7 +188,7 @@ class HttpHost {
187
188
  }
188
189
  const address = match[1] || hostname;
189
190
  const ma = +(/ma=(\d+)/.exec(match[3])?.[1] || 86400);
190
- if (!this[kAltSvcError].includes(`h${i + 1}:${address}:${port}`)) {
191
+ if (!excluded.includes(`h${i + 1}:${address}:${port}`)) {
191
192
  addresses.push([
192
193
  address,
193
194
  port,
@@ -278,11 +279,7 @@ class HttpHost {
278
279
  this.closeAltSvc();
279
280
  this[kAltSvcQueue] = [];
280
281
  this[kAltSvcError] = [];
281
- this[kVersionData].forEach(item => {
282
- if (item[3] !== 0) {
283
- item[4] = -1;
284
- }
285
- });
282
+ this[kVersionData].forEach(item => item[3] && (item[4] = -1));
286
283
  }
287
284
  }
288
285
  flagAltSvc(version, value) {
package/index.js CHANGED
@@ -53,6 +53,8 @@ const DNS = {
53
53
  };
54
54
  const ARIA2 = {
55
55
  BIN: which.sync(PLATFORM_WIN32 ? 'aria2c.exe' : 'aria2c', { nothrow: true }) || '',
56
+ EXEC_UID: undefined,
57
+ EXEC_GID: undefined,
56
58
  PID_TIMER: null,
57
59
  PID_QUEUE: [],
58
60
  UPDATE_STATUS: 0,
@@ -76,6 +78,14 @@ let AGENT_TIMEOUT = 0;
76
78
  let LOG_HTTP = false;
77
79
  let LOG_TIMEPROCESS = true;
78
80
  let LOG_TIMEFORMAT = 'readable';
81
+ let LIB_ZSTD = null;
82
+ try {
83
+ require('zstd-codec/lib/zstd-stream').run(codec => {
84
+ LIB_ZSTD = codec;
85
+ });
86
+ }
87
+ catch {
88
+ }
79
89
  function getBaseHeaders(uri, headers) {
80
90
  uri = (0, util_1.trimPath)(uri);
81
91
  let result;
@@ -122,7 +132,7 @@ function setOutgoingHeaders(output, headers) {
122
132
  }
123
133
  function getProxySettings(request, agentTimeout) {
124
134
  const proxy = request.proxy;
125
- if ((0, types_1.isObject)(proxy) && proxy.address && proxy.port) {
135
+ if (proxy?.address && proxy.port) {
126
136
  const port = (0, util_1.asInt)(proxy.port);
127
137
  const address = (!module_1.default.isURL(proxy.address) ? port === 80 ? 'http://' : 'https://' : '') + proxy.address;
128
138
  try {
@@ -144,11 +154,9 @@ function getProxySettings(request, agentTimeout) {
144
154
  return null;
145
155
  }
146
156
  function closeTorrent(pid) {
147
- if (pid !== undefined) {
148
- const index = ARIA2.PID_QUEUE.findIndex(value => pid === value[0]);
149
- if (index !== -1) {
150
- ARIA2.PID_QUEUE.splice(index, 1);
151
- }
157
+ const index = ARIA2.PID_QUEUE.findIndex(value => pid === value[0]);
158
+ if (index !== -1) {
159
+ ARIA2.PID_QUEUE.splice(index, 1);
152
160
  }
153
161
  }
154
162
  function clearDnsLookup() {
@@ -266,7 +274,7 @@ class Request extends module_1.default {
266
274
  if (!this.enabled("process.password") || super.loadSettings({ process: settings.process }, password)) {
267
275
  const { request, download } = settings;
268
276
  if (download && (0, types_1.isPlainObject)(download.aria2)) {
269
- let { bin, update_status, max_concurrent_downloads, max_connection_per_server, bt_stop_timeout, bt_tracker_connect_timeout, bt_tracker_timeout, min_split_size, disk_cache, lowest_speed_limit, always_resume, file_allocation, conf_path } = download.aria2;
277
+ let { bin, exec, update_status, max_concurrent_downloads, max_connection_per_server, bt_stop_timeout, bt_tracker_connect_timeout, bt_tracker_timeout, min_split_size, disk_cache, lowest_speed_limit, always_resume, file_allocation, conf_path } = download.aria2;
270
278
  const parseSize = (value, zero) => {
271
279
  if (zero && (value === '0' || value === 0)) {
272
280
  return 0;
@@ -281,6 +289,11 @@ class Request extends module_1.default {
281
289
  else if (bin && this.isPath(bin = path.resolve(bin), true)) {
282
290
  ARIA2.BIN = bin;
283
291
  }
292
+ if ((0, types_1.isPlainObject)(exec)) {
293
+ let { uid, gid } = exec;
294
+ ARIA2.EXEC_UID = (uid = (0, util_1.asInt)(uid)) >= 0 ? uid : undefined;
295
+ ARIA2.EXEC_GID = (gid = (0, util_1.asInt)(gid)) >= 0 ? gid : undefined;
296
+ }
284
297
  if ((0, types_1.isPlainObject)(update_status)) {
285
298
  const { interval, broadcast_only } = update_status;
286
299
  if (typeof broadcast_only === 'boolean') {
@@ -409,124 +422,141 @@ class Request extends module_1.default {
409
422
  return url.protocol + '//' + (auth && (auth + '@')) + url.hostname + (url.port ? ':' + url.port : '') + (!value.startsWith('/') ? '/' : '') + value;
410
423
  }
411
424
  static fromStatusCode(value) {
412
- switch (+value) {
413
- case 100:
414
- return 'Continue';
415
- case 101:
416
- return 'Switching Protocol';
417
- case 102:
418
- return 'Processing';
419
- case 103:
420
- return 'Early Hints';
421
- case 200:
422
- return 'OK';
423
- case 201:
424
- return 'Created';
425
- case 202:
426
- return 'Accepted';
427
- case 203:
428
- return 'Non-Authoritative Information';
429
- case 204:
430
- return 'No Content';
431
- case 205:
432
- return 'Reset Content';
433
- case 206:
434
- return 'Partial Content';
435
- case 300:
436
- return 'Multiple Choice';
437
- case 301:
438
- return 'Moved Permanently';
439
- case 302:
440
- return 'Found';
441
- case 303:
442
- return 'See Other';
443
- case 304:
444
- return 'Not Modified';
445
- case 305:
446
- return 'Use Proxy';
447
- case 307:
448
- return 'Temporary Redirect';
449
- case 308:
450
- return 'Permanent Redirect';
451
- case 400:
452
- return 'Bad Request';
453
- case 401:
454
- return 'Upgrade Required';
455
- case 402:
456
- return 'Payment Required';
457
- case 403:
458
- return 'Forbidden';
459
- case 404:
460
- return 'Not Found';
461
- case 405:
462
- return 'Method Not Allowed';
463
- case 406:
464
- return 'Not Acceptable';
465
- case 407:
466
- return 'Proxy Authentication Required';
467
- case 408:
468
- return 'Request Timeout';
469
- case 409:
470
- return 'Conflict';
471
- case 410:
472
- return 'Gone';
473
- case 411:
474
- return 'Length Required';
475
- case 412:
476
- return 'Precondition Failed';
477
- case 413:
478
- return 'Payload Too Large';
479
- case 414:
480
- return 'URI Too Long';
481
- case 415:
482
- return 'Unsupported Media Type';
483
- case 416:
484
- return 'Range Not Satisfiable';
485
- case 417:
486
- return 'Expectation Failed';
487
- case 421:
488
- return 'Misdirected Request';
489
- case 422:
490
- return 'Unprocessable Entity';
491
- case 423:
492
- return 'Locked';
493
- case 424:
494
- return 'Failed Dependency';
495
- case 426:
496
- return 'Upgrade Required';
497
- case 428:
498
- return 'Precondition Required';
499
- case 429:
500
- return 'Too Many Requests';
501
- case 431:
502
- return 'Request Header Fields Too Large';
503
- case 451:
504
- return 'Unavailable For Legal Reasons';
505
- case 500:
506
- return 'Internal Server Error';
507
- case 501:
508
- return 'Not Implemented';
509
- case 502:
510
- return 'Bad Gateway';
511
- case 503:
512
- return 'Service Unavailable';
513
- case 504:
514
- return 'Gateway Timeout';
515
- case 505:
516
- return 'HTTP Version Not Supported';
517
- case 506:
518
- return 'Variant Also Negotiates';
519
- case 507:
520
- return 'Insufficient Storage';
521
- case 508:
522
- return 'Loop Detected';
523
- case 510:
524
- return 'Not Extended';
525
- case 511:
526
- return 'Network Authentication Required';
527
- default:
528
- return "Unknown";
425
+ if ((value = +value) < 200) {
426
+ switch (value) {
427
+ case 100:
428
+ return 'Continue';
429
+ case 101:
430
+ return 'Switching Protocol';
431
+ case 102:
432
+ return 'Processing';
433
+ case 103:
434
+ return 'Early Hints';
435
+ }
436
+ }
437
+ else if (value < 300) {
438
+ switch (value) {
439
+ case 200:
440
+ return 'OK';
441
+ case 201:
442
+ return 'Created';
443
+ case 202:
444
+ return 'Accepted';
445
+ case 203:
446
+ return 'Non-Authoritative Information';
447
+ case 204:
448
+ return 'No Content';
449
+ case 205:
450
+ return 'Reset Content';
451
+ case 206:
452
+ return 'Partial Content';
453
+ }
454
+ }
455
+ else if (value < 400) {
456
+ switch (value) {
457
+ case 300:
458
+ return 'Multiple Choice';
459
+ case 301:
460
+ return 'Moved Permanently';
461
+ case 302:
462
+ return 'Found';
463
+ case 303:
464
+ return 'See Other';
465
+ case 304:
466
+ return 'Not Modified';
467
+ case 305:
468
+ return 'Use Proxy';
469
+ case 307:
470
+ return 'Temporary Redirect';
471
+ case 308:
472
+ return 'Permanent Redirect';
473
+ }
474
+ }
475
+ else if (value < 500) {
476
+ switch (value) {
477
+ case 400:
478
+ return 'Bad Request';
479
+ case 401:
480
+ return 'Upgrade Required';
481
+ case 402:
482
+ return 'Payment Required';
483
+ case 403:
484
+ return 'Forbidden';
485
+ case 404:
486
+ return 'Not Found';
487
+ case 405:
488
+ return 'Method Not Allowed';
489
+ case 406:
490
+ return 'Not Acceptable';
491
+ case 407:
492
+ return 'Proxy Authentication Required';
493
+ case 408:
494
+ return 'Request Timeout';
495
+ case 409:
496
+ return 'Conflict';
497
+ case 410:
498
+ return 'Gone';
499
+ case 411:
500
+ return 'Length Required';
501
+ case 412:
502
+ return 'Precondition Failed';
503
+ case 413:
504
+ return 'Payload Too Large';
505
+ case 414:
506
+ return 'URI Too Long';
507
+ case 415:
508
+ return 'Unsupported Media Type';
509
+ case 416:
510
+ return 'Range Not Satisfiable';
511
+ case 417:
512
+ return 'Expectation Failed';
513
+ case 421:
514
+ return 'Misdirected Request';
515
+ case 422:
516
+ return 'Unprocessable Entity';
517
+ case 423:
518
+ return 'Locked';
519
+ case 424:
520
+ return 'Failed Dependency';
521
+ case 426:
522
+ return 'Upgrade Required';
523
+ case 428:
524
+ return 'Precondition Required';
525
+ case 429:
526
+ return 'Too Many Requests';
527
+ case 431:
528
+ return 'Request Header Fields Too Large';
529
+ case 451:
530
+ return 'Unavailable For Legal Reasons';
531
+ }
529
532
  }
533
+ else {
534
+ switch (value) {
535
+ case 500:
536
+ return 'Internal Server Error';
537
+ case 501:
538
+ return 'Not Implemented';
539
+ case 502:
540
+ return 'Bad Gateway';
541
+ case 503:
542
+ return 'Service Unavailable';
543
+ case 504:
544
+ return 'Gateway Timeout';
545
+ case 505:
546
+ return 'HTTP Version Not Supported';
547
+ case 506:
548
+ return 'Variant Also Negotiates';
549
+ case 507:
550
+ return 'Insufficient Storage';
551
+ case 508:
552
+ return 'Loop Detected';
553
+ case 510:
554
+ return 'Not Extended';
555
+ case 511:
556
+ return 'Network Authentication Required';
557
+ }
558
+ }
559
+ return "Unknown";
530
560
  }
531
561
  static defineHttpAgent(options) {
532
562
  const { keepAlive, timeout = 0 } = options;
@@ -610,11 +640,8 @@ class Request extends module_1.default {
610
640
  this.readTimeout = (value = (0, util_1.fromSeconds)(read_timeout)) >= 0 ? value : READ_TIMEOUT;
611
641
  this.keepAlive = typeof (value = agent?.keep_alive) === 'boolean' ? value : KEEP_ALIVE;
612
642
  this.acceptEncoding = typeof (value = use?.accept_encoding) === 'boolean' ? value : ACCEPT_ENCODING;
613
- switch (value = (0, util_1.asInt)(use?.http_version)) {
614
- case 1:
615
- case 2:
616
- this[kHttpVersion] = value;
617
- break;
643
+ if ((value = (0, util_1.asInt)(use?.http_version)) === 1 || value === 2) {
644
+ this[kHttpVersion] = value;
618
645
  }
619
646
  this[kIpVersion] = (value = (0, util_1.asInt)(data.dns?.family)) && (value === 4 || value === 6) ? value : 0;
620
647
  if ((value = (0, util_1.fromSeconds)(agent?.timeout)) >= 0) {
@@ -802,28 +829,26 @@ class Request extends module_1.default {
802
829
  return this;
803
830
  }
804
831
  addDns(hostname, address, family) {
805
- if (!this[kConnectDns][hostname]) {
806
- switch (family) {
807
- case 'IPv4':
832
+ switch (family) {
833
+ case 'IPv4':
834
+ family = 4;
835
+ break;
836
+ case 'IPv6':
837
+ family = 6;
838
+ break;
839
+ default:
840
+ if (net.isIPv4(address)) {
808
841
  family = 4;
809
- break;
810
- case 'IPv6':
842
+ }
843
+ else if (net.isIPv6(address)) {
811
844
  family = 6;
812
- break;
813
- default:
814
- if (net.isIPv4(address)) {
815
- family = 4;
816
- }
817
- else if (net.isIPv6(address)) {
818
- family = 6;
819
- }
820
- else {
821
- return;
822
- }
823
- break;
824
- }
825
- setDnsCache(hostname, this[kConnectDns][hostname] = [{ address, family }]);
845
+ }
846
+ else {
847
+ return;
848
+ }
849
+ break;
826
850
  }
851
+ setDnsCache(hostname, this[kConnectDns][hostname] = [{ address, family }]);
827
852
  }
828
853
  lookupDns(hostname) {
829
854
  var _l;
@@ -893,17 +918,18 @@ class Request extends module_1.default {
893
918
  }
894
919
  proxyOf(uri, localhost) {
895
920
  const proxy = this.proxy || this.host && HTTP.PROXY;
896
- if (proxy) {
897
- const { include, exclude } = proxy;
898
- if (!include && !exclude && !localhost) {
899
- return proxy;
900
- }
901
- if ((0, types_1.isArray)(include)) {
902
- return include.some(value => uri.startsWith(value)) ? proxy : undefined;
903
- }
904
- if (Array.isArray(exclude) && !exclude.some(value => uri.startsWith(value))) {
905
- return proxy;
906
- }
921
+ if (!proxy) {
922
+ return;
923
+ }
924
+ const { include, exclude } = proxy;
925
+ if (!include && !exclude && !localhost) {
926
+ return proxy;
927
+ }
928
+ if ((0, types_1.isArray)(include)) {
929
+ return include.some(value => uri.startsWith(value)) ? proxy : undefined;
930
+ }
931
+ if (Array.isArray(exclude) && !exclude.some(value => uri.startsWith(value))) {
932
+ return proxy;
907
933
  }
908
934
  }
909
935
  headersOf(uri) {
@@ -1164,7 +1190,7 @@ class Request extends module_1.default {
1164
1190
  closeTorrent(pid);
1165
1191
  reject(err);
1166
1192
  };
1167
- const { pid, stdout, stderr } = child_process.spawn(module_1.default.sanitizeCmd(ARIA2.BIN), args, { cwd: pathname, shell: true, signal: this.signal })
1193
+ const { pid, stdout, stderr } = child_process.spawn(module_1.default.sanitizeCmd(ARIA2.BIN), args, { cwd: pathname, shell: true, signal: this.signal, uid: ARIA2.EXEC_UID, gid: ARIA2.EXEC_GID })
1168
1194
  .on('exit', code => {
1169
1195
  closeTorrent(pid);
1170
1196
  if (aborted) {
@@ -1352,6 +1378,11 @@ class Request extends module_1.default {
1352
1378
  case 'deflate-raw':
1353
1379
  pipeTo = zlib.createInflateRaw({ chunkSize });
1354
1380
  break;
1381
+ case 'zstd':
1382
+ if (LIB_ZSTD) {
1383
+ pipeTo = new LIB_ZSTD.ZstdDecompressTransform({ writableHighWaterMark: chunkSize });
1384
+ }
1385
+ break;
1355
1386
  }
1356
1387
  if (pipeTo) {
1357
1388
  if (outStream) {
@@ -1363,21 +1394,22 @@ class Request extends module_1.default {
1363
1394
  return pipeTo;
1364
1395
  }
1365
1396
  };
1366
- const { hostname, origin } = host;
1397
+ const { hostname, origin, secure, localhost } = host;
1367
1398
  const pathname = url.pathname + (socketPath ? '' : url.search);
1368
- const proxy = this.proxyOf(uri, host.localhost);
1399
+ const proxy = this.proxyOf(uri, localhost);
1400
+ const version = this.httpVersion;
1369
1401
  let request, ca, cert, key, minVersion, baseHeaders = this.headersOf(uri);
1370
- if (getting && this.acceptEncoding && !host.localhost && !baseHeaders?.['accept-encoding']) {
1371
- (_l = (headers || (headers = {})))['accept-encoding'] || (_l['accept-encoding'] = 'gzip, deflate, br');
1402
+ if (getting && this.acceptEncoding && !localhost && !baseHeaders?.['accept-encoding']) {
1403
+ (_l = (headers || (headers = {})))['accept-encoding'] || (_l['accept-encoding'] = 'gzip, deflate, br' + (LIB_ZSTD ? ', zstd' : ''));
1372
1404
  }
1373
- if (host.secure) {
1374
- const secure = this[kCerts]?.[0][origin] || (this.host ? TLS.TEXT[origin] : null);
1375
- if (secure) {
1376
- ({ ca, cert, key, version: minVersion } = secure);
1405
+ if (secure) {
1406
+ const certs = this[kCerts]?.[0][origin] || (this.host ? TLS.TEXT[origin] : null);
1407
+ if (certs) {
1408
+ ({ ca, cert, key, version: minVersion } = certs);
1377
1409
  }
1378
1410
  }
1379
- if (!proxy && httpVersion !== 1 && ((httpVersion || host.version) === 2 && this.httpVersion !== 1 || host.secure && this.httpVersion === 2 && host.failed(2, true) === 0)) {
1380
- request = ((_m = this[kSession][0])[origin] || (_m[origin] = http2.connect(origin, { lookup: this.lookupDns(hostname), ca, cert, key, minVersion }))).request({ ...baseHeaders, ...host_1.default.getBasicAuth(url), ...headers, ':path': pathname, ':method': method });
1411
+ if (!proxy && httpVersion !== 1 && ((httpVersion || host.version) === 2 && version !== 1 || secure && version === 2 && host.failed(2, true) === 0)) {
1412
+ request = ((_m = this[kSession][0])[origin] || (_m[origin] = http2.connect(origin, { lookup: this.lookupDns(hostname), ca, cert, key, minVersion, settings: localhost ? { maxFrameSize: 16777215, enablePush: false } : { enablePush: false } }))).request({ ...baseHeaders, ...host_1.default.getBasicAuth(url), ...headers, ':path': pathname, ':method': method });
1381
1413
  if (getting) {
1382
1414
  const listenerMap = {};
1383
1415
  const onEvent = request.on.bind(request);
@@ -1457,7 +1489,7 @@ class Request extends module_1.default {
1457
1489
  let agent;
1458
1490
  if (!socketPath) {
1459
1491
  if (proxy) {
1460
- const pkg = host.secure ? 'https-proxy-agent' : 'http-proxy-agent';
1492
+ const pkg = secure ? 'https-proxy-agent' : 'http-proxy-agent';
1461
1493
  try {
1462
1494
  const { protocol, hostname: proxyname, port, username, password, href } = proxy.host;
1463
1495
  keepAlive ?? (keepAlive = proxy.keepAlive || false);
@@ -1473,16 +1505,16 @@ class Request extends module_1.default {
1473
1505
  }
1474
1506
  }
1475
1507
  else if (keepAlive === false) {
1476
- agent = new (host.secure ? https.Agent : http.Agent)({ keepAlive: false });
1508
+ agent = new (secure ? https.Agent : http.Agent)({ keepAlive: false });
1477
1509
  }
1478
1510
  else if (keepAlive === true || agentTimeout > 0) {
1479
- agent = new (host.secure ? https.Agent : http.Agent)({ keepAlive: true, timeout: agentTimeout });
1511
+ agent = new (secure ? https.Agent : http.Agent)({ keepAlive: true, timeout: agentTimeout });
1480
1512
  }
1481
1513
  else if (agentTimeout !== 0) {
1482
1514
  keepAlive = this.keepAlive || false;
1483
1515
  agentTimeout ?? (agentTimeout = this.agentTimeout);
1484
1516
  if (keepAlive || agentTimeout > 0) {
1485
- agent = new (host.secure ? https.Agent : http.Agent)({ keepAlive, timeout: agentTimeout });
1517
+ agent = new (secure ? https.Agent : http.Agent)({ keepAlive, timeout: agentTimeout });
1486
1518
  }
1487
1519
  }
1488
1520
  }
@@ -1490,7 +1522,7 @@ class Request extends module_1.default {
1490
1522
  if (baseHeaders || basicAuth) {
1491
1523
  headers = { ...baseHeaders, ...basicAuth, ...headers };
1492
1524
  }
1493
- request = (host.secure ? https : http).request(socketPath ? { socketPath, path: pathname } : {
1525
+ request = (secure ? https : http).request(socketPath ? { socketPath, path: pathname } : {
1494
1526
  protocol: host.protocol,
1495
1527
  hostname,
1496
1528
  port: host.port,
@@ -1506,7 +1538,8 @@ class Request extends module_1.default {
1506
1538
  }, response => {
1507
1539
  const statusCode = response.statusCode;
1508
1540
  if ((getting || posting) && statusCode >= 200 && statusCode < 300) {
1509
- let source = checkEncoding(response, statusCode, response.headers['content-encoding']);
1541
+ const incoming = response.headers;
1542
+ let source = checkEncoding(response, statusCode, incoming['content-encoding']);
1510
1543
  if (source) {
1511
1544
  source.once('finish', () => request.emit('end'));
1512
1545
  }
@@ -1537,8 +1570,13 @@ class Request extends module_1.default {
1537
1570
  if (response !== source) {
1538
1571
  source.on('error', err => request.emit('error', err));
1539
1572
  }
1540
- if (!posting && !host.didAltSvc(1)) {
1541
- host.upgrade(1, response.headers['alt-svc']);
1573
+ if (!posting) {
1574
+ if (version === 2 && incoming.upgrade?.includes('h2')) {
1575
+ host.version = 2;
1576
+ }
1577
+ else if (!host.didAltSvc(1)) {
1578
+ host.upgrade(1, incoming['alt-svc']);
1579
+ }
1542
1580
  }
1543
1581
  if (LOG_HTTP) {
1544
1582
  this[kConnectHttp][0][origin] = (this[kConnectHttp][0][origin] || 0) + 1;
@@ -1614,11 +1652,9 @@ class Request extends module_1.default {
1614
1652
  }
1615
1653
  const headers = options.headers || (options.headers = {});
1616
1654
  for (const attr in headers) {
1617
- switch (attr.toLowerCase()) {
1618
- case 'content-type':
1619
- case 'content-length':
1620
- delete headers[attr];
1621
- break;
1655
+ const name = attr.toLowerCase();
1656
+ if (name === 'content-type' || name === 'content-length') {
1657
+ delete headers[attr];
1622
1658
  }
1623
1659
  }
1624
1660
  if (parts || contentType === "multipart/form-data" || contentType === 'form-data') {
@@ -1649,53 +1685,54 @@ class Request extends module_1.default {
1649
1685
  }
1650
1686
  }
1651
1687
  for (let { name, data: target, value, contentType: type, filename } of parts) {
1652
- if ((0, types_1.isString)(name)) {
1653
- if (target) {
1654
- try {
1655
- if (typeof target === 'string') {
1656
- filename || (filename = path.basename(target));
1657
- type || (type = module_1.default.lookupMime(filename));
1658
- target = fs.readFileSync(target);
1688
+ if (!(0, types_1.isString)(name)) {
1689
+ continue;
1690
+ }
1691
+ if (target) {
1692
+ try {
1693
+ if (typeof target === 'string') {
1694
+ filename || (filename = path.basename(target));
1695
+ type || (type = module_1.default.lookupMime(filename));
1696
+ target = fs.readFileSync(target);
1697
+ }
1698
+ else if (target instanceof stream.Readable) {
1699
+ const chunks = [];
1700
+ for await (const chunk of target) {
1701
+ chunks.push(chunk);
1659
1702
  }
1660
- else if (target instanceof stream.Readable) {
1661
- const chunks = [];
1662
- for await (const chunk of target) {
1663
- chunks.push(chunk);
1664
- }
1665
- target = Buffer.concat(chunks);
1703
+ target = Buffer.concat(chunks);
1704
+ }
1705
+ if (!Buffer.isBuffer(target)) {
1706
+ throw (0, types_1.errorMessage)('File', "Unknown", "multipart/form-data");
1707
+ }
1708
+ if (!type || !filename) {
1709
+ const result = await module_1.default.resolveMime(target);
1710
+ let ext;
1711
+ if (result) {
1712
+ type || (type = result.mime);
1713
+ ext = result.ext;
1666
1714
  }
1667
- if (!Buffer.isBuffer(target)) {
1668
- throw (0, types_1.errorMessage)('File', "Unknown", "multipart/form-data");
1715
+ else if (type) {
1716
+ ext = module_1.default.lookupMime(type, true);
1669
1717
  }
1670
- if (!type || !filename) {
1671
- const result = await module_1.default.resolveMime(target);
1672
- let ext;
1673
- if (result) {
1674
- type || (type = result.mime);
1675
- ext = result.ext;
1676
- }
1677
- else if (type) {
1678
- ext = module_1.default.lookupMime(type, true);
1679
- }
1680
- if (ext && !filename) {
1681
- filename = (0, types_1.generateUUID)() + '.' + ext;
1682
- }
1718
+ if (ext && !filename) {
1719
+ filename = (0, types_1.generateUUID)() + '.' + ext;
1683
1720
  }
1684
- const disposition = createPart(name, filename, type || "application/octet-stream");
1685
- write.append(disposition);
1686
- write.append(target);
1687
- write.append("\r\n");
1688
- contentLength += Buffer.byteLength(disposition) + target.length + 2;
1689
- valid = true;
1690
- }
1691
- catch (err) {
1692
- return Promise.reject(err);
1693
1721
  }
1722
+ const disposition = createPart(name, filename, type || "application/octet-stream");
1723
+ write.append(disposition);
1724
+ write.append(target);
1725
+ write.append("\r\n");
1726
+ contentLength += Buffer.byteLength(disposition) + target.length + 2;
1727
+ valid = true;
1694
1728
  }
1695
- else {
1696
- addValue(name, value);
1729
+ catch (err) {
1730
+ return Promise.reject(err);
1697
1731
  }
1698
1732
  }
1733
+ else {
1734
+ addValue(name, value);
1735
+ }
1699
1736
  }
1700
1737
  if (valid) {
1701
1738
  write.append("--" + boundary + "--" + "\r\n");
@@ -1711,17 +1748,15 @@ class Request extends module_1.default {
1711
1748
  if (contentType && !contentType.includes('/')) {
1712
1749
  contentType = 'application/' + contentType.trim();
1713
1750
  }
1714
- if ((0, types_1.isPlainObject)(data)) {
1715
- if (contentType === "application/x-www-form-urlencoded") {
1716
- data = qs.stringify(data);
1717
- }
1718
- else {
1719
- data = JSON.stringify(data);
1720
- contentType || (contentType = "application/json");
1721
- }
1751
+ if (!(0, types_1.isPlainObject)(data)) {
1752
+ data = module_1.default.asString(data);
1753
+ }
1754
+ else if (contentType === "application/x-www-form-urlencoded") {
1755
+ data = qs.stringify(data);
1722
1756
  }
1723
1757
  else {
1724
- data = module_1.default.asString(data);
1758
+ data = JSON.stringify(data);
1759
+ contentType || (contentType = "application/json");
1725
1760
  }
1726
1761
  headers['content-length'] = Buffer.byteLength(data, (0, types_1.getEncoding)(dataEncoding)).toString();
1727
1762
  }
@@ -1817,14 +1852,15 @@ class Request extends module_1.default {
1817
1852
  const buffering = request.connected?.call(client, headers);
1818
1853
  const pipeline = pipeTo ? !(0, types_1.isString)(pipeTo) : false;
1819
1854
  const enabled = buffering !== false && !pipeline;
1855
+ const readTimeout = this.readTimeout;
1820
1856
  let mibsTime, delayTime;
1821
- if (log || this.readTimeout > 0) {
1857
+ if (log || readTimeout > 0) {
1822
1858
  client.once('readable', () => {
1823
- if (this.readTimeout > 0) {
1859
+ if (readTimeout > 0) {
1824
1860
  timeout = setTimeout(() => {
1825
1861
  abortResponse();
1826
1862
  throwError((0, types_1.errorValue)("Timeout was exceeded", href.toString()));
1827
- }, this.readTimeout);
1863
+ }, readTimeout);
1828
1864
  }
1829
1865
  if (log) {
1830
1866
  if (buffering === false) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e-mc/request",
3
- "version": "0.5.4",
3
+ "version": "0.6.1",
4
4
  "description": "Request constructor for E-mc.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "repository": {
11
11
  "type": "git",
12
- "url": "git+https://github.com/anpham6/e-mc.git",
12
+ "url": "https://github.com/anpham6/e-mc.git",
13
13
  "directory": "src/request"
14
14
  },
15
15
  "keywords": [
@@ -20,8 +20,8 @@
20
20
  "license": "MIT",
21
21
  "homepage": "https://github.com/anpham6/e-mc#readme",
22
22
  "dependencies": {
23
- "@e-mc/module": "0.5.4",
24
- "@e-mc/types": "0.5.4",
23
+ "@e-mc/module": "0.6.1",
24
+ "@e-mc/types": "0.6.1",
25
25
  "combined-stream": "^1.0.8",
26
26
  "js-yaml": "^4.1.0",
27
27
  "which": "^2.0.2"
package/util.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /// <reference path="../types/lib/object.d.ts" />
2
+
1
3
  import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
2
4
 
3
5
  declare namespace util {