fetch-har 5.0.5 → 6.0.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
@@ -13,13 +13,17 @@ npm install --save fetch-har
13
13
 
14
14
  ## Usage
15
15
  ```js
16
- const fetchHar = require('fetch-har');
16
+ require('isomorphic-fetch');
17
+ const fetchHar = require('.');
17
18
 
18
- // If executing from an environment without `fetch`, you'll need to polyfill.
19
- global.fetch = require('node-fetch');
20
- global.Headers = require('node-fetch').Headers;
21
- global.Request = require('node-fetch').Request;
22
- global.FormData = require('form-data');
19
+ // If executing from an environment that dodoesn't normally provide fetch()
20
+ // you'll need to polyfill some APIs in order to make `multipart/form-data`
21
+ // requests.
22
+ if (!globalThis.FormData) {
23
+ globalThis.Blob = require('formdata-node').Blob;
24
+ globalThis.File = require('formdata-node').File;
25
+ globalThis.FormData = require('formdata-node').FormData;
26
+ }
23
27
 
24
28
  const har = {
25
29
  log: {
@@ -36,7 +40,10 @@ const har = {
36
40
  value: 'application/json',
37
41
  },
38
42
  ],
39
- queryString: [{ name: 'a', value: 1 }, { name: 'b', value: 2 }],
43
+ queryString: [
44
+ { name: 'a', value: 1 },
45
+ { name: 'b', value: 2 },
46
+ ],
40
47
  postData: {
41
48
  mimeType: 'application/json',
42
49
  text: '{"id":8,"category":{"id":6,"name":"name"},"name":"name"}',
@@ -50,22 +57,48 @@ const har = {
50
57
  };
51
58
 
52
59
  fetchHar(har)
53
- .then(request => request.json())
60
+ .then(res => res.json())
54
61
  .then(console.log);
55
62
  ```
56
63
 
57
- ### `fetchHar(har, userAgent) => Promise`
64
+ ### API
65
+ If you are executing `fetch-har` in a browser environment that supports the [FormData API](https://developer.mozilla.org/en-US/docs/Web/API/FormData) then you don't need to do anything. If you arent, however, you'll need to polyfill it.
66
+
67
+ Unfortunately the most popular NPM package [form-data](https://npm.im/form-data) ships with a [non-spec compliant API](https://github.com/form-data/form-data/issues/124), and for this we don't recommend you use it, as if you use `fetch-har` to upload files it may not work.
68
+
69
+ We recommend either [formdata-node](https://npm.im/formdata-node) or [formdata-polyfill](https://npm.im/formdata-polyfill).
70
+
71
+ #### Options
72
+ ##### userAgent
73
+ A custom `User-Agent` header to apply to your request. Please note that browsers have their own handling for these headers in `fetch()` calls so it may not work everywhere; it will always be sent in Node however.
74
+
75
+ ```js
76
+ await fetchHar(har, { userAgent: 'my-client/1.0' });
77
+ ```
78
+
79
+ ##### files
80
+ An optional object map you can supply to use for `multipart/form-data` file uploads in leu of relying on if the HAR you have has [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). It supports Node file buffers and the [File](https://developer.mozilla.org/en-US/docs/Web/API/File) API.
81
+
82
+ ```js
83
+ await fetchHar(har, { files: {
84
+ 'owlbert.png': await fs.readFile('./owlbert.png'),
85
+ 'file.txt': document.querySelector('#some-file-input').files[0],
86
+ } });
87
+ ```
58
88
 
59
- - `har` is a [har](https://en.wikipedia.org/wiki/.har) file format.
60
- - `userAgent` is an optional user agent string to let you declare where the request is coming from.
89
+ If you don't supply this option `fetch-har` will fallback to the data URL present within the supplied HAR. If no `files` option is present, and no data URL (via `param.value`) is present in the HAR, a fatal exception will be thrown.
61
90
 
62
- Performs a fetch request from a given HAR definition. HAR definitions can be used to list lots of requests but we only use the first from the `log.entries` array.
91
+ ##### multipartEncoder
92
+ > ❗ If you are using `fetch-har` in Node you may need this option!
63
93
 
64
- ### `fetchHar.constructRequest(har, userAgent) => Request`
94
+ If you are running `fetch-har` within a Node environment and you're using `node-fetch@2`, or another `fetch` polyfill that does not support a spec-compliant `FormData` API, you will need to specify an encoder that will transform your `FormData` object into something that can be used with [Request.body](https://developer.mozilla.org/en-US/docs/Web/API/Request/body).
65
95
 
66
- - `har` is a [har](https://en.wikipedia.org/wiki/.har) file format.
67
- - `userAgent` is an optional user agent string to let you declare where the request is coming from.
96
+ We recommend [form-data-encoder](https://npm.im/form-data-encoder).
68
97
 
69
- We also export a second function which is used to construct a [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object from your HAR.
98
+ ```js
99
+ const { FormDataEncoder } = require('form-data-encoder');
100
+
101
+ await fetchHar(har, { multipartEncoder: FormDataEncoder });
102
+ ```
70
103
 
71
- This function is mainly exported for testing purposes but could be useful if you want to construct a request but do not want to execute it right away.
104
+ You do **not**, and shouldn't, need to use this option in browser environments.
package/example.js CHANGED
@@ -1,11 +1,14 @@
1
1
  /* eslint-disable import/no-extraneous-dependencies, no-console */
2
+ require('isomorphic-fetch');
2
3
  const fetchHar = require('.');
3
4
 
4
- // If executing from an environment without `fetch`, you'll need to polyfill
5
- global.fetch = require('node-fetch');
6
- global.Headers = require('node-fetch').Headers;
7
- global.Request = require('node-fetch').Request;
8
- global.FormData = require('form-data');
5
+ // If executing from an environment that dodoesn't normally provide fetch() you'll need to polyfill some APIs in order
6
+ // to make `multipart/form-data` requests.
7
+ if (!globalThis.FormData) {
8
+ globalThis.Blob = require('formdata-node').Blob;
9
+ globalThis.File = require('formdata-node').File;
10
+ globalThis.FormData = require('formdata-node').FormData;
11
+ }
9
12
 
10
13
  const har = {
11
14
  log: {
@@ -39,5 +42,5 @@ const har = {
39
42
  };
40
43
 
41
44
  fetchHar(har)
42
- .then(request => request.json())
45
+ .then(res => res.json())
43
46
  .then(console.log);
package/index.js CHANGED
@@ -1,7 +1,76 @@
1
- /* eslint-disable no-case-declarations */
1
+ const { Readable } = require('readable-stream');
2
2
  const parseDataUrl = require('parse-data-url');
3
3
 
4
- function constructRequest(har, userAgent = false) {
4
+ if (!globalThis.Blob) {
5
+ try {
6
+ // eslint-disable-next-line import/no-extraneous-dependencies
7
+ globalThis.Blob = require('formdata-node').Blob;
8
+ } catch (e) {
9
+ throw new Error(
10
+ 'Since you do not have the Blob API available in this environment you must install the optional `formdata-node` dependency.'
11
+ );
12
+ }
13
+ }
14
+
15
+ if (!globalThis.File) {
16
+ try {
17
+ // eslint-disable-next-line import/no-extraneous-dependencies
18
+ globalThis.File = require('formdata-node').File;
19
+ } catch (e) {
20
+ throw new Error(
21
+ 'Since you do not have the File API available in this environment you must install the optional `formdata-node` dependency.'
22
+ );
23
+ }
24
+ }
25
+
26
+ function isBrowser() {
27
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
28
+ }
29
+
30
+ function isBuffer(value) {
31
+ return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);
32
+ }
33
+
34
+ function isFile(value) {
35
+ if (value instanceof File) {
36
+ // The `Blob` polyfill on Node comes back as being an instanceof `File`. Because passing a Blob into
37
+ // a File will end up with a corrupted file we want to prevent this.
38
+ //
39
+ // This object identity crisis does not happen in the browser.
40
+ return value.constructor.name === 'File';
41
+ }
42
+
43
+ return false;
44
+ }
45
+
46
+ /**
47
+ * @license MIT
48
+ * @see {@link https://github.com/octet-stream/form-data-encoder/blob/master/lib/util/isFunction.ts}
49
+ */
50
+ function isFunction(value) {
51
+ return typeof value === 'function';
52
+ }
53
+
54
+ /**
55
+ * We're loading this library in here instead of loading it from `form-data-encoder` because that uses lookbehind
56
+ * regex in its main encoder that Safari doesn't support so it throws a fatal page exception.
57
+ *
58
+ * @license MIT
59
+ * @see {@link https://github.com/octet-stream/form-data-encoder/blob/master/lib/util/isFormData.ts}
60
+ */
61
+ function isFormData(value) {
62
+ return (
63
+ value &&
64
+ isFunction(value.constructor) &&
65
+ value[Symbol.toStringTag] === 'FormData' && // eslint-disable-line compat/compat
66
+ isFunction(value.append) &&
67
+ isFunction(value.getAll) &&
68
+ isFunction(value.entries) &&
69
+ isFunction(value[Symbol.iterator]) // eslint-disable-line compat/compat
70
+ );
71
+ }
72
+
73
+ function constructRequest(har, opts = { userAgent: false, files: false, multipartEncoder: false }) {
5
74
  if (!har) throw new Error('Missing HAR definition');
6
75
  if (!har.log || !har.log.entries || !har.log.entries.length) throw new Error('Missing log.entries array');
7
76
 
@@ -31,7 +100,7 @@ function constructRequest(har, userAgent = false) {
31
100
  // As the browser fetch API can't set custom cookies for requests, they instead need to be defined on the document
32
101
  // and passed into the request via `credentials: include`. Since this is a browser-specific quirk, that should only
33
102
  // happen in browsers!
34
- if (typeof window !== 'undefined' && typeof document !== 'undefined') {
103
+ if (isBrowser()) {
35
104
  request.cookies.forEach(cookie => {
36
105
  document.cookie = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`;
37
106
  });
@@ -68,7 +137,10 @@ function constructRequest(har, userAgent = false) {
68
137
  options.body = encodedParams.toString();
69
138
  break;
70
139
 
140
+ case 'multipart/alternative':
71
141
  case 'multipart/form-data':
142
+ case 'multipart/mixed':
143
+ case 'multipart/related':
72
144
  // If there's a Content-Type header set remove it. We're doing this because when we pass the form data object
73
145
  // into `fetch` that'll set a proper `Content-Type` header for this request that also includes the boundary
74
146
  // used on the content.
@@ -79,59 +151,93 @@ function constructRequest(har, userAgent = false) {
79
151
  headers.delete('Content-Type');
80
152
  }
81
153
 
82
- // The `form-data` NPM module returns one of two things: a native `FormData` API, or its own polyfill. Since
83
- // the polyfill does not support the full API of the native FormData object, when you load `form-data` within
84
- // a browser environment you'll have two major differences in API:
85
- //
86
- // * The `.append()` API in `form-data` requires that the third argument is an object containing various,
87
- // undocumented, options. In the browser, `.append()`'s third argument should only be present when the
88
- // second is a `Blob` or `USVString`, and when it is present, it should be a filename string.
89
- // * `form-data` does not expose an `.entries()` API, so the only way to retrieve data out of it for
90
- // construction of boundary-separated payload content is to use its `.pipe()` API. Since the browser
91
- // doesn't have this API, you'll be unable to retrieve data out of it.
92
- //
93
- // Now since the native `FormData` API is iterable, and has the `.entries()` iterator, we can easily detect
94
- // what version of the FormData API we have access to by looking for this and constructing a simple wrapper
95
- // to disconnect some of this logic so you can work against a single, consistent API.
96
- //
97
- // Having to do this isn't fun, but it's the only way you can write code to work with `multipart/form-data`
98
- // content under a server and browser.
99
154
  const form = new FormData();
100
- const isNativeFormData = typeof form[Symbol.iterator] === 'function';
155
+ if (!isFormData(form)) {
156
+ // The `form-data` NPM module returns one of two things: a native `FormData` API or its own polyfill.
157
+ // Unfortunately this polyfill does not support the full API of the native FormData object so when you load
158
+ // `form-data` within a browser environment you'll have two major differences in API:
159
+ //
160
+ // * The `.append()` API in `form-data` requires that the third argument is an object containing various,
161
+ // undocumented, options. In the browser, `.append()`'s third argument should only be present when the
162
+ // second is a `Blob` or `USVString`, and when it is present, it should be a filename string.
163
+ // * `form-data` does not expose an `.entries()` API, so the only way to retrieve data out of it for
164
+ // construction of boundary-separated payload content is to use its `.pipe()` API. Since the browser
165
+ // doesn't have this API, you'll be unable to retrieve data out of it.
166
+ //
167
+ // Now since the native `FormData` API is iterable, and has the `.entries()` iterator, we can easily detect
168
+ // if we have a native copy of the FormData API. It's for all of these reasons that we're opting to hard
169
+ // crash here because supporting this non-compliant API is more trouble than its worth.
170
+ //
171
+ // https://github.com/form-data/form-data/issues/124
172
+ throw new Error(
173
+ "We've detected you're using a non-spec compliant FormData library. We recommend polyfilling FormData with https://npm.im/formdata-node"
174
+ );
175
+ }
101
176
 
102
177
  request.postData.params.forEach(param => {
103
- if ('fileName' in param && !('value' in param)) {
104
- throw new Error(
105
- "The supplied HAR has a postData parameter with `fileName`, but no `value` content. Since this library doesn't have access to the filesystem, it can't fetch that file."
106
- );
107
- }
108
-
109
- // If the incoming parameter is a file, and that files value is a data URL, we should decode that and set
110
- // the contents of the value in the HAR to the actual contents of the file.
111
178
  if ('fileName' in param) {
112
- const parsed = parseDataUrl(param.value);
113
- if (parsed) {
114
- // eslint-disable-next-line no-param-reassign
115
- param.value = parsed.toBuffer().toString();
116
- }
117
- }
179
+ if (opts.files && param.fileName in opts.files) {
180
+ const fileContents = opts.files[param.fileName];
181
+
182
+ // If the file we've got available to us is a Buffer then we need to convert it so that the FormData
183
+ // API can use it.
184
+ if (isBuffer(fileContents)) {
185
+ form.set(
186
+ param.name,
187
+ new File([fileContents], param.fileName, {
188
+ type: param.contentType || null,
189
+ }),
190
+ param.fileName
191
+ );
192
+
193
+ return;
194
+ } else if (isFile(fileContents)) {
195
+ form.set(param.name, fileContents, param.fileName);
196
+ return;
197
+ }
198
+
199
+ throw new TypeError(
200
+ 'An unknown object has been supplied into the `files` config for use. We only support instances of the File API and Node Buffer objects.'
201
+ );
202
+ } else if ('value' in param) {
203
+ let paramBlob;
204
+ const parsed = parseDataUrl(param.value);
205
+ if (parsed) {
206
+ // If we were able to parse out this data URL we don't need to transform its data into a buffer for
207
+ // `Blob` because that supports data URLs already.
208
+ paramBlob = new Blob([param.value], { type: parsed.contentType || param.contentType || null });
209
+ } else {
210
+ paramBlob = new Blob([param.value], { type: param.contentType || null });
211
+ }
118
212
 
119
- if (isNativeFormData) {
120
- if ('fileName' in param) {
121
- const paramBlob = new Blob([param.value], { type: param.contentType || null });
122
213
  form.append(param.name, paramBlob, param.fileName);
123
- } else {
124
- form.append(param.name, param.value);
214
+ return;
125
215
  }
126
- } else {
127
- form.append(param.name, param.value || '', {
128
- filename: param.fileName || null,
129
- contentType: param.contentType || null,
130
- });
216
+
217
+ throw new Error(
218
+ "The supplied HAR has a postData parameter with `fileName`, but neither `value` content within the HAR or any file buffers were supplied with the `files` option. Since this library doesn't have access to the filesystem, it can't fetch that file."
219
+ );
131
220
  }
221
+
222
+ form.append(param.name, param.value);
132
223
  });
133
224
 
134
- options.body = form;
225
+ // If a the `fetch` polyfill that's being used here doesn't have spec-compliant handling for the `FormData`
226
+ // API (like `node-fetch@2`), then you should pass in a handler (like the `form-data-encoder` library) to
227
+ // transform its contents into something that can be used with the `Request` object.
228
+ //
229
+ // https://www.npmjs.com/package/formdata-node
230
+ if (opts.multipartEncoder) {
231
+ // eslint-disable-next-line new-cap
232
+ const encoder = new opts.multipartEncoder(form);
233
+ Object.keys(encoder.headers).forEach(header => {
234
+ headers.set(header, encoder.headers[header]);
235
+ });
236
+
237
+ options.body = Readable.from(encoder);
238
+ } else {
239
+ options.body = form;
240
+ }
135
241
  break;
136
242
 
137
243
  default:
@@ -148,27 +254,59 @@ function constructRequest(har, userAgent = false) {
148
254
 
149
255
  options.body = JSON.stringify(formBody);
150
256
  }
151
- } else {
152
- options.body = request.postData.text;
257
+ } else if (request.postData.text.length) {
258
+ // If we've got `files` map content present, and this post data content contains a valid data URL then we can
259
+ // substitute the payload with that file instead of the using data URL.
260
+ if (opts.files) {
261
+ const parsed = parseDataUrl(request.postData.text);
262
+ if (parsed && 'name' in parsed && parsed.name in opts.files) {
263
+ const fileContents = opts.files[parsed.name];
264
+ if (isBuffer(fileContents)) {
265
+ options.body = fileContents;
266
+ } else if (isFile(fileContents)) {
267
+ // `Readable.from` isn't available in browsers but the browser `Request` object can handle `File` objects
268
+ // just fine without us having to mold it into shape.
269
+ if (isBrowser()) {
270
+ options.body = fileContents;
271
+ } else {
272
+ options.body = Readable.from(fileContents.stream());
273
+
274
+ // Supplying a polyfilled `File` stream into `Request.body` doesn't automatically add `Content-Length`.
275
+ if (!headers.has('content-length')) {
276
+ headers.set('content-length', fileContents.size);
277
+ }
278
+ }
279
+ }
280
+ }
281
+ }
282
+
283
+ if (typeof options.body === 'undefined') {
284
+ options.body = request.postData.text;
285
+ }
153
286
  }
154
287
  }
155
288
 
156
289
  if ('queryString' in request && request.queryString.length) {
157
- const query = request.queryString.map(q => `${q.name}=${q.value}`).join('&');
158
- querystring = `?${query}`;
290
+ const queryParams = new URL(url).searchParams;
291
+
292
+ request.queryString.forEach(q => {
293
+ queryParams.append(q.name, q.value);
294
+ });
295
+
296
+ querystring = queryParams.toString();
159
297
  }
160
298
 
161
- if (userAgent) {
162
- headers.append('User-Agent', userAgent);
299
+ if (opts.userAgent) {
300
+ headers.append('User-Agent', opts.userAgent);
163
301
  }
164
302
 
165
303
  options.headers = headers;
166
304
 
167
- return new Request(`${url}${querystring}`, options);
305
+ return new Request(`${url.split('?')[0]}${querystring ? `?${querystring}` : ''}`, options);
168
306
  }
169
307
 
170
- function fetchHar(har, userAgent) {
171
- return fetch(constructRequest(har, userAgent));
308
+ function fetchHar(har, opts = { userAgent: false, files: false, multipartEncoder: false }) {
309
+ return fetch(constructRequest(har, opts));
172
310
  }
173
311
 
174
312
  module.exports = fetchHar;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fetch-har",
3
- "version": "5.0.5",
3
+ "version": "6.0.0",
4
4
  "description": "Make a fetch request from a HAR definition",
5
5
  "main": "index.js",
6
6
  "engines": {
@@ -12,7 +12,10 @@
12
12
  "prettier": "prettier --list-different --write \"./**.js\"",
13
13
  "release": "npx conventional-changelog-cli -i CHANGELOG.md -s",
14
14
  "serve": "node __tests__/server.js",
15
- "test": "jest --coverage"
15
+ "test:browser": "karma start --single-run",
16
+ "test:browser:chrome": "karma start --browsers=Chrome --single-run=false",
17
+ "test:browser:debug": "karma start --single-run=false",
18
+ "test": "nyc mocha"
16
19
  },
17
20
  "repository": {
18
21
  "type": "git",
@@ -24,37 +27,32 @@
24
27
  },
25
28
  "homepage": "https://github.com/readmeio/fetch-har#readme",
26
29
  "dependencies": {
27
- "parse-data-url": "^4.0.1"
30
+ "parse-data-url": "^4.0.1",
31
+ "readable-stream": "^3.6.0"
32
+ },
33
+ "optionalDependencies": {
34
+ "fromdata-node": "^4.3.2"
28
35
  },
29
36
  "devDependencies": {
30
- "@readme/eslint-config": "^8.0.2",
31
- "body-parser": "^1.19.0",
32
- "cookie-parser": "^1.4.5",
33
- "eslint": "^8.2.0",
34
- "eslint-plugin-compat": "^4.0.0",
35
- "express": "^4.17.1",
37
+ "@jsdevtools/host-environment": "^2.1.2",
38
+ "@jsdevtools/karma-config": "^3.1.7",
39
+ "@readme/eslint-config": "^8.1.2",
40
+ "chai": "^4.3.4",
41
+ "eslint": "^8.7.0",
42
+ "eslint-plugin-compat": "^4.0.1",
43
+ "eslint-plugin-mocha": "^10.0.3",
36
44
  "form-data": "^4.0.0",
37
- "har-examples": "^2.0.1",
38
- "jest": "^27.2.0",
39
- "jest-puppeteer": "^6.0.0",
40
- "multer": "^1.4.2",
41
- "nock": "^13.1.1",
45
+ "form-data-encoder": "^1.7.1",
46
+ "formdata-node": "^4.3.2",
47
+ "har-examples": "^3.0.0",
48
+ "isomorphic-fetch": "^3.0.0",
49
+ "mocha": "^9.1.4",
42
50
  "node-fetch": "^2.6.0",
43
- "prettier": "^2.4.1",
44
- "webpack": "^5.53.0",
45
- "webpack-dev-middleware": "^5.1.0"
51
+ "nyc": "^15.1.0",
52
+ "prettier": "^2.5.1"
46
53
  },
47
54
  "browserslist": [
48
55
  "last 2 versions"
49
56
  ],
50
- "prettier": "@readme/eslint-config/prettier",
51
- "jest": {
52
- "preset": "jest-puppeteer",
53
- "globals": {
54
- "SERVER_URL": "http://localhost:4444"
55
- },
56
- "testMatch": [
57
- "<rootDir>/__tests__/*.test.js"
58
- ]
59
- }
57
+ "prettier": "@readme/eslint-config/prettier"
60
58
  }
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- server: {
3
- command: 'npm run serve',
4
- port: 4444,
5
- },
6
- };