rekwest 3.3.4 → 4.1.0

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/README.md CHANGED
@@ -1,186 +1,187 @@
1
- The robust request library that humanity deserves 🌐
2
- ---
3
- This package provides highly likely functional and **easy-to-use** abstraction atop of
4
- native [http(s).request](https://nodejs.org/api/https.html#https_https_request_url_options_callback)
5
- and [http2.request](https://nodejs.org/api/http2.html#http2_clienthttp2session_request_headers_options).
6
-
7
- ## Abstract
8
-
9
- * Fetch-alike
10
- * Cool-beans 🫐 config options (with defaults)
11
- * Automatic HTTP/2 support (ALPN negotiation)
12
- * Automatic or opt-in body parse (with non-UTF-8 charset decoding)
13
- * Automatic and simplistic `Cookies` treatment (with built-in jar)
14
- * Automatic decompression (with opt-in body compression)
15
- * Built-in streamable `File` & `FormData` interfaces
16
- * Support redirects & retries with fine-grained tune-ups
17
- * Support all legit request body types (include blobs & streams)
18
- * Support both CJS and ESM module systems
19
- * Fully promise-able and pipe-able
20
- * Zero dependencies
21
-
22
- ## Prerequisites
23
-
24
- * Node.js `>= 16.5.x`
25
-
26
- ## Installation
27
-
28
- ```bash
29
- npm install rekwest --save
30
- ```
31
-
32
- ### Usage
33
-
34
- ```javascript
35
- import rekwest, { constants } from 'rekwest';
36
-
37
- const {
38
- HTTP2_HEADER_AUTHORIZATION,
39
- HTTP2_HEADER_CONTENT_ENCODING,
40
- HTTP2_METHOD_POST,
41
- HTTP_STATUS_OK,
42
- } = constants;
43
-
44
- const url = 'https://somewhe.re/somewhat/endpoint';
45
-
46
- const res = await rekwest(url, {
47
- body: { celestial: 'payload' },
48
- headers: {
49
- [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
50
- [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
51
- /** [HTTP2_HEADER_CONTENT_TYPE]
52
- * is undue for
53
- * Array/Blob/File/FormData/Object/URLSearchParams body types
54
- * and will be set automatically, with an option to override it here
55
- */
56
- },
57
- method: HTTP2_METHOD_POST,
58
- });
59
-
60
- console.assert(res.statusCode === HTTP_STATUS_OK);
61
- console.info(res.headers);
62
- console.log(res.body);
63
- ```
64
-
65
- ---
66
-
67
- ```javascript
68
- import rekwest, {
69
- constants,
70
- Blob,
71
- File,
72
- FormData,
73
- } from 'rekwest';
74
- import { Readable } from 'node:stream';
75
-
76
- const {
77
- HTTP2_HEADER_AUTHORIZATION,
78
- HTTP2_HEADER_CONTENT_ENCODING,
79
- HTTP2_METHOD_POST,
80
- HTTP_STATUS_OK,
81
- } = constants;
82
-
83
- const blob = new Blob(['bits']);
84
- const file = new File(['bits'], 'file.dab');
85
- const readable = Readable.from('bits');
86
-
87
- const fd = new FormData({
88
- aux: Date.now(), // either [[key, value]], or kv sequenceable
89
- });
90
-
91
- fd.append('celestial', 'payload');
92
- fd.append('blob', blob, 'blob.dab');
93
- fd.append('file', file);
94
- fd.append('readable', readable, 'readable.dab');
95
-
96
- const url = 'https://somewhe.re/somewhat/endpoint';
97
-
98
- const res = await rekwest(url, {
99
- body: fd,
100
- headers: {
101
- [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
102
- [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
103
- },
104
- method: HTTP2_METHOD_POST,
105
- });
106
-
107
- console.assert(res.statusCode === HTTP_STATUS_OK);
108
- console.info(res.headers);
109
- console.log(res.body);
110
- ```
111
-
112
- ### API
113
-
114
- #### `rekwest(url[, options])`
115
-
116
- * `url` **{string | URL}** The URL to send the request to
117
- * `options` **{Object}**
118
- Extends [https.RequestOptions](https://nodejs.org/api/https.html#https_https_request_url_options_callback)
119
- along with
120
- extra [http2.ClientSessionOptions](https://nodejs.org/api/http2.html#http2_http2_connect_authority_options_listener)
121
- & [http2.ClientSessionRequestOptions](https://nodejs.org/api/http2.html#http2_clienthttp2session_request_headers_options)
122
- and [tls.ConnectionOptions](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback)
123
- for HTTP/2 attunes
124
- * `body` **{string | Array | ArrayBuffer | ArrayBufferView | AsyncIterator | Blob | Buffer | DataView | File |
125
- FormData | Iterator | Object | Readable | SharedArrayBuffer | URLSearchParams}** The body to send with the request
126
- * `cookies` **{boolean | Array<[k, v]> | Cookies | Object | URLSearchParams}** `Default: true` The cookies to add to
127
- the request
128
- * `digest` **{boolean}** `Default: true` Controls whether to read the response stream or simply add a mixin
129
- * `follow` **{number}** `Default: 20` The number of redirects to follow
130
- * `h2` **{boolean}** `Default: false` Forces the use of HTTP/2 protocol
131
- * `headers` **{Object}** The headers to add to the request
132
- * `maxRetryAfter` **{number}** The upper limit of `retry-after` header. If unset, it will use `timeout` value
133
- * `parse` **{boolean}** `Default: true` Controls whether to parse response body or simply return a buffer
134
- * `redirect` **{error | follow | manual}** `Default: follow` Controls the redirect flows
135
- * `retry` **{Object}** Represents the retry options
136
- * `attempts` **{number}** `Default: 0` The number of retry attempts
137
- * `backoffStrategy` **{string}** `Default: interval * Math.log(Math.random() * (Math.E * Math.E - Math.E) + Math.E)`
138
- The backoff strategy algorithm that increases logarithmically. To fixate set value to `interval * 1`
139
- * `interval` **{number}** `Default: 1e3` The initial retry interval
140
- * `retryAfter` **{boolean}** `Default: true` Controls `retry-after` header receptiveness
141
- * `statusCodes` **{number[]}** `Default: [429, 503]` The list of status codes to retry on
142
- * `thenable` **{boolean}** `Default: false` Controls the promise resolutions
143
- * `timeout` **{number}** `Default: 3e5` The number of milliseconds a request can take before termination
144
- * `trimTrailingSlashes` **{boolean}** `Default: false` Controls whether to trim trailing slashes in the URL before
145
- proceed with the request
146
- * **Returns:** Promise that resolves to
147
- extended [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
148
- or [http2.ClientHttp2Stream](https://nodejs.org/api/http2.html#http2_class_clienthttp2stream) which is respectively
149
- readable and duplex streams
150
- * if `degist: true` & `parse: true`
151
- * `body` **{string | Array | Buffer | Object}** The body based on its content type
152
- * if `degist: false`
153
- * `arrayBuffer` **{AsyncFunction}** Reads the response and returns **ArrayBuffer**
154
- * `blob` **{AsyncFunction}** Reads the response and returns **Blob**
155
- * `body` **{AsyncFunction}** Reads the response and returns **Buffer** if `parse: false`
156
- * `json` **{AsyncFunction}** Reads the response and returns **Object**
157
- * `text` **{AsyncFunction}** Reads the response and returns **String**
158
- * `bodyUsed` **{boolean}** Indicates whether the response were read or not
159
- * `cookies` **{undefined | Cookies}** The cookies sent and received with the response
160
- * `headers` **{Object}** The headers received with the response
161
- * `httpVersion` **{string}** Indicates protocol version negotiated with the server
162
- * `ok` **{boolean}** Indicates if the response was successful (statusCode: **200-299**)
163
- * `redirected` **{boolean}** Indicates if the response is the result of a redirect
164
- * `statusCode` **{number}** Indicates the status code of the response
165
- * `trailers` **{undefined | Object}** The trailer headers received with the response
166
-
167
- ---
168
-
169
- #### `rekwest.defaults`
170
-
171
- The object to fulfill with default [options](#rekwesturl-options)
172
-
173
- ---
174
-
175
- #### `rekwest.stream(url[, options])`
176
-
177
- The method with limited functionality to use with streams and/or pipes
178
-
179
- * No automata
180
- * No redirects
181
- * Pass `h2: true` in options to use HTTP/2 protocol
182
- * Or use `ackn({ url: URL })` method in advance to probe the available protocols
183
-
184
- ---
185
-
186
- For more details, please check tests (coverage: **>97%**) in the repository
1
+ The robust request library that humanity deserves 🌐
2
+ ---
3
+ This package provides highly likely functional and **easy-to-use** abstraction atop of
4
+ native [http(s).request](https://nodejs.org/api/https.html#https_https_request_url_options_callback)
5
+ and [http2.request](https://nodejs.org/api/http2.html#http2_clienthttp2session_request_headers_options).
6
+
7
+ ## Abstract
8
+
9
+ * Fetch-alike
10
+ * Cool-beans 🫐 config options (with defaults)
11
+ * Automatic HTTP/2 support (ALPN negotiation)
12
+ * Automatic or opt-in body parse (with non-UTF-8 charset decoding)
13
+ * Automatic and simplistic `Cookies` treatment (with built-in jar)
14
+ * Automatic decompression (with opt-in body compression)
15
+ * Built-in streamable `File` & `FormData` interfaces
16
+ * Support redirects & retries with fine-grained tune-ups
17
+ * Support all legit request body types (include blobs & streams)
18
+ * Support both CJS and ESM module systems
19
+ * Fully promise-able and pipe-able
20
+ * Zero dependencies
21
+
22
+ ## Prerequisites
23
+
24
+ * Node.js `>= 16.7.x`
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install rekwest --save
30
+ ```
31
+
32
+ ### Usage
33
+
34
+ ```javascript
35
+ import rekwest, { constants } from 'rekwest';
36
+
37
+ const {
38
+ HTTP2_HEADER_AUTHORIZATION,
39
+ HTTP2_HEADER_CONTENT_ENCODING,
40
+ HTTP2_METHOD_POST,
41
+ HTTP_STATUS_OK,
42
+ } = constants;
43
+
44
+ const url = 'https://somewhe.re/somewhat/endpoint';
45
+
46
+ const res = await rekwest(url, {
47
+ body: { celestial: 'payload' },
48
+ headers: {
49
+ [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
50
+ [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
51
+ /** [HTTP2_HEADER_CONTENT_TYPE]
52
+ * is undue for
53
+ * Array/Blob/File/FormData/Object/URLSearchParams body types
54
+ * and will be set automatically, with an option to override it here
55
+ */
56
+ },
57
+ method: HTTP2_METHOD_POST,
58
+ });
59
+
60
+ console.assert(res.statusCode === HTTP_STATUS_OK);
61
+ console.info(res.headers);
62
+ console.log(res.body);
63
+ ```
64
+
65
+ ---
66
+
67
+ ```javascript
68
+ import rekwest, {
69
+ constants,
70
+ Blob,
71
+ File,
72
+ FormData,
73
+ } from 'rekwest';
74
+ import { Readable } from 'node:stream';
75
+
76
+ const {
77
+ HTTP2_HEADER_AUTHORIZATION,
78
+ HTTP2_HEADER_CONTENT_ENCODING,
79
+ HTTP2_METHOD_POST,
80
+ HTTP_STATUS_OK,
81
+ } = constants;
82
+
83
+ const blob = new Blob(['bits']);
84
+ const file = new File(['bits'], 'file.dab');
85
+ const readable = Readable.from('bits');
86
+
87
+ const fd = new FormData({
88
+ aux: Date.now(), // either [[key, value]], or kv sequenceable
89
+ });
90
+
91
+ fd.append('celestial', 'payload');
92
+ fd.append('blob', blob, 'blob.dab');
93
+ fd.append('file', file);
94
+ fd.append('readable', readable, 'readable.dab');
95
+
96
+ const url = 'https://somewhe.re/somewhat/endpoint';
97
+
98
+ const res = await rekwest(url, {
99
+ body: fd,
100
+ headers: {
101
+ [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
102
+ [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
103
+ },
104
+ method: HTTP2_METHOD_POST,
105
+ });
106
+
107
+ console.assert(res.statusCode === HTTP_STATUS_OK);
108
+ console.info(res.headers);
109
+ console.log(res.body);
110
+ ```
111
+
112
+ ### API
113
+
114
+ #### `rekwest(url[, options])`
115
+
116
+ * `url` **{string | URL}** The URL to send the request to
117
+ * `options` **{Object}**
118
+ Extends [https.RequestOptions](https://nodejs.org/api/https.html#https_https_request_url_options_callback)
119
+ along with
120
+ extra [http2.ClientSessionOptions](https://nodejs.org/api/http2.html#http2_http2_connect_authority_options_listener)
121
+ & [http2.ClientSessionRequestOptions](https://nodejs.org/api/http2.html#http2_clienthttp2session_request_headers_options)
122
+ and [tls.ConnectionOptions](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback)
123
+ for HTTP/2 attunes
124
+ * `body` **{string | Array | ArrayBuffer | ArrayBufferView | AsyncIterator | Blob | Buffer | DataView | File |
125
+ FormData | Iterator | Object | Readable | ReadableStream | SharedArrayBuffer | URLSearchParams}** The body to send
126
+ with the request
127
+ * `cookies` **{boolean | Array<[k, v]> | Cookies | Object | URLSearchParams}** `Default: true` The cookies to add to
128
+ the request
129
+ * `digest` **{boolean}** `Default: true` Controls whether to read the response stream or simply add a mixin
130
+ * `follow` **{number}** `Default: 20` The number of redirects to follow
131
+ * `h2` **{boolean}** `Default: false` Forces the use of HTTP/2 protocol
132
+ * `headers` **{Object}** The headers to add to the request
133
+ * `maxRetryAfter` **{number}** The upper limit of `retry-after` header. If unset, it will use `timeout` value
134
+ * `parse` **{boolean}** `Default: true` Controls whether to parse response body or simply return a buffer
135
+ * `redirect` **{error | follow | manual}** `Default: follow` Controls the redirect flows
136
+ * `retry` **{Object}** Represents the retry options
137
+ * `attempts` **{number}** `Default: 0` The number of retry attempts
138
+ * `backoffStrategy` **{string}** `Default: interval * Math.log(Math.random() * (Math.E * Math.E - Math.E) + Math.E)`
139
+ The backoff strategy algorithm that increases logarithmically. To fixate set value to `interval * 1`
140
+ * `interval` **{number}** `Default: 1e3` The initial retry interval
141
+ * `retryAfter` **{boolean}** `Default: true` Controls `retry-after` header receptiveness
142
+ * `statusCodes` **{number[]}** `Default: [429, 503]` The list of status codes to retry on
143
+ * `thenable` **{boolean}** `Default: false` Controls the promise resolutions
144
+ * `timeout` **{number}** `Default: 3e5` The number of milliseconds a request can take before termination
145
+ * `trimTrailingSlashes` **{boolean}** `Default: false` Controls whether to trim trailing slashes in the URL before
146
+ proceed with the request
147
+ * **Returns:** Promise that resolves to
148
+ extended [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
149
+ or [http2.ClientHttp2Stream](https://nodejs.org/api/http2.html#http2_class_clienthttp2stream) which is respectively
150
+ readable and duplex streams
151
+ * if `degist: true` & `parse: true`
152
+ * `body` **{string | Array | Buffer | Object}** The body based on its content type
153
+ * if `degist: false`
154
+ * `arrayBuffer` **{AsyncFunction}** Reads the response and returns **ArrayBuffer**
155
+ * `blob` **{AsyncFunction}** Reads the response and returns **Blob**
156
+ * `body` **{AsyncFunction}** Reads the response and returns **Buffer** if `parse: false`
157
+ * `json` **{AsyncFunction}** Reads the response and returns **Object**
158
+ * `text` **{AsyncFunction}** Reads the response and returns **String**
159
+ * `bodyUsed` **{boolean}** Indicates whether the response were read or not
160
+ * `cookies` **{undefined | Cookies}** The cookies sent and received with the response
161
+ * `headers` **{Object}** The headers received with the response
162
+ * `httpVersion` **{string}** Indicates protocol version negotiated with the server
163
+ * `ok` **{boolean}** Indicates if the response was successful (statusCode: **200-299**)
164
+ * `redirected` **{boolean}** Indicates if the response is the result of a redirect
165
+ * `statusCode` **{number}** Indicates the status code of the response
166
+ * `trailers` **{undefined | Object}** The trailer headers received with the response
167
+
168
+ ---
169
+
170
+ #### `rekwest.defaults`
171
+
172
+ The object to fulfill with default [options](#rekwesturl-options)
173
+
174
+ ---
175
+
176
+ #### `rekwest.stream(url[, options])`
177
+
178
+ The method with limited functionality to use with streams and/or pipes
179
+
180
+ * No automata
181
+ * No redirects
182
+ * Pass `h2: true` in options to use HTTP/2 protocol
183
+ * Use `ackn({ url: URL })` method beforehand to check the available protocols
184
+
185
+ ---
186
+
187
+ For more details, please check tests (coverage: **>97%**) in the repository
package/dist/ackn.js CHANGED
@@ -2,14 +2,13 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.ackn = void 0;
5
-
6
5
  var _nodeTls = require("node:tls");
7
-
8
6
  const ackn = options => new Promise((resolve, reject) => {
9
7
  const {
10
8
  url
11
9
  } = options;
12
- const socket = (0, _nodeTls.connect)({ ...options,
10
+ const socket = (0, _nodeTls.connect)({
11
+ ...options,
13
12
  ALPNProtocols: ['h2', 'http/1.1'],
14
13
  host: url.hostname,
15
14
  port: parseInt(url.port) || 443,
@@ -20,13 +19,12 @@ const ackn = options => new Promise((resolve, reject) => {
20
19
  const {
21
20
  alpnProtocol
22
21
  } = socket;
23
- resolve({ ...options,
22
+ resolve({
23
+ ...options,
24
24
  alpnProtocol,
25
-
26
25
  createConnection() {
27
26
  return socket;
28
27
  },
29
-
30
28
  h2: /h2c?/.test(alpnProtocol),
31
29
  protocol: url.protocol
32
30
  });
@@ -34,5 +32,4 @@ const ackn = options => new Promise((resolve, reject) => {
34
32
  socket.on('error', reject);
35
33
  socket.on('timeout', reject);
36
34
  });
37
-
38
35
  exports.ackn = ackn;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.redirectStatusCodes = exports.redirectModes = void 0;
5
+ var _nodeHttp = _interopRequireDefault(require("node:http2"));
6
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
7
+ const {
8
+ HTTP_STATUS_FOUND,
9
+ HTTP_STATUS_MOVED_PERMANENTLY,
10
+ HTTP_STATUS_PERMANENT_REDIRECT,
11
+ HTTP_STATUS_SEE_OTHER,
12
+ HTTP_STATUS_TEMPORARY_REDIRECT
13
+ } = _nodeHttp.default.constants;
14
+ const redirectModes = {
15
+ error: 'error',
16
+ follow: 'follow',
17
+ manual: 'manual'
18
+ };
19
+ exports.redirectModes = redirectModes;
20
+ const redirectStatusCodes = [HTTP_STATUS_MOVED_PERMANENTLY, HTTP_STATUS_FOUND, HTTP_STATUS_SEE_OTHER, HTTP_STATUS_TEMPORARY_REDIRECT, HTTP_STATUS_PERMANENT_REDIRECT];
21
+ exports.redirectStatusCodes = redirectStatusCodes;
package/dist/cookies.js CHANGED
@@ -2,29 +2,21 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.Cookies = void 0;
5
-
6
- var _utils = require("./utils.js");
7
-
5
+ var _utils = require("./utils");
8
6
  class Cookies extends URLSearchParams {
9
7
  static jar = new Map();
10
-
11
8
  get [Symbol.toStringTag]() {
12
9
  return this.constructor.name;
13
10
  }
14
-
15
11
  constructor(input) {
16
12
  if (Array.isArray(input) && input.every(it => !Array.isArray(it))) {
17
- input = input.join(';').split(';').filter(it => !/\b(Domain|Expires|HttpOnly|Max-Age|Path|SameParty|SameSite|Secure)\b/i.test(it)).map(it => it.trim()).join('&');
13
+ input = input.join(';').split(';').filter(it => !/\b(?:Domain|Expires|HttpOnly|Max-Age|Path|SameParty|SameSite|Secure)\b/i.test(it)).map(it => it.trim()).join('&');
18
14
  }
19
-
20
15
  super(input);
21
16
  }
22
-
23
17
  toString() {
24
- (0, _utils.collate)(this, Cookies);
18
+ (0, _utils.brandCheck)(this, Cookies);
25
19
  return super.toString().split('&').join('; ').trim();
26
20
  }
27
-
28
21
  }
29
-
30
22
  exports.Cookies = Cookies;
package/dist/errors.js CHANGED
@@ -2,25 +2,18 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.TimeoutError = exports.RequestError = void 0;
5
-
6
5
  class RequestError extends Error {
7
6
  get [Symbol.toStringTag]() {
8
7
  return this.constructor.name;
9
8
  }
10
-
11
9
  get name() {
12
10
  return this[Symbol.toStringTag];
13
11
  }
14
-
15
12
  constructor(...args) {
16
13
  super(...args);
17
14
  Error.captureStackTrace(this, this.constructor);
18
15
  }
19
-
20
16
  }
21
-
22
17
  exports.RequestError = RequestError;
23
-
24
18
  class TimeoutError extends RequestError {}
25
-
26
19
  exports.TimeoutError = TimeoutError;
package/dist/file.js CHANGED
@@ -2,41 +2,36 @@
2
2
 
3
3
  exports.__esModule = true;
4
4
  exports.File = void 0;
5
-
6
5
  var _nodeBuffer = require("node:buffer");
7
-
8
6
  exports.Blob = _nodeBuffer.Blob;
9
-
7
+ var _nodeUtil = require("node:util");
10
8
  class File extends _nodeBuffer.Blob {
11
9
  static alike(instance) {
12
10
  return [_nodeBuffer.Blob.name, File.name].includes(instance?.constructor.name);
13
11
  }
14
-
15
12
  #lastModified;
16
13
  #name;
17
-
18
14
  get [Symbol.toStringTag]() {
19
15
  return this.constructor.name;
20
16
  }
21
-
22
17
  get lastModified() {
23
18
  return this.#lastModified;
24
19
  }
25
-
26
20
  get name() {
27
21
  return this.#name;
28
22
  }
29
-
30
- constructor(bits, name = 'blob', options = {}) {
23
+ constructor(...args) {
24
+ const len = args.length;
25
+ if (len < 2) {
26
+ throw new TypeError(`Failed to construct '${File.name}': 2 arguments required, but only ${len} present.`);
27
+ }
28
+ const [bits, name, options = {}] = args;
31
29
  const {
32
- name: filename,
33
30
  lastModified = Date.now()
34
31
  } = options;
35
32
  super(bits, options);
36
- this.#lastModified = lastModified;
37
- this.#name = filename || name;
33
+ this.#lastModified = +lastModified ? lastModified : 0;
34
+ this.#name = (0, _nodeUtil.toUSVString)(name);
38
35
  }
39
-
40
36
  }
41
-
42
37
  exports.File = File;