Skip to content

Commit 4d7e628

Browse files
committed
Tweaks
1 parent a268250 commit 4d7e628

39 files changed

+467
-411
lines changed

documentation/2-options.md

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,11 @@ await got('https://httpbin.org/anything');
116116
await got(new URL('https://httpbin.org/anything'));
117117
```
118118

119-
#### **Note:**
120-
> - Throws if no protocol specified.
119+
> [!NOTE]
120+
> Throws if no protocol specified.
121121
122-
#### **Note:**
123-
> - If `url` is a string, then the `query` string will **not** be parsed as search params.\
122+
> [!NOTE]
123+
> If `url` is a string, then the `query` string will **not** be parsed as search params.\
124124
> This is in accordance to [the specification](https://datatracker.ietf.org/doc/html/rfc7230#section-2.7).\
125125
> If you want to pass search params instead, use the `searchParams` option below.
126126
@@ -134,8 +134,8 @@ await got('https://httpbin.org/anything', {searchParams: {query: 'a b'}}); //=>
134134
await got('https://httpbin.org/anything?query=a b', {searchParams: {query: 'a b'}}); //=> ?query=a+b
135135
```
136136

137-
#### **Note:**
138-
> - Leading slashes are disallowed to enforce consistency and avoid confusion.\
137+
> [!NOTE]
138+
> Leading slashes are disallowed to enforce consistency and avoid confusion.\
139139
> For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. The latter is used by browsers.
140140
141141
### `searchParams`
@@ -171,10 +171,10 @@ console.log(searchParams.toString());
171171
//=> 'key=a&key=b'
172172
```
173173

174-
#### **Note:**
175-
> - This will override the `query` string in `url`.
174+
> [!NOTE]
175+
> This will override the `query` string in `url`.
176176
177-
#### **Note:**
177+
> [!NOTE]
178178
> - `null` values are not stringified, an empty string is used instead.
179179
> - `undefined` values will clear the original keys.
180180
@@ -202,11 +202,11 @@ await instance('anything');
202202
await got('https://httpbin.org/anything');
203203
```
204204

205-
#### **Note:**
206-
> - Changing `prefixUrl` also updates the `url` option if set.
205+
> [!NOTE]
206+
> Changing `prefixUrl` also updates the `url` option if set.
207207
208-
#### **Note:**
209-
> - If you're passing an absolute URL as `url`, you need to set `prefixUrl` to an empty string.
208+
> [!NOTE]
209+
> If you're passing an absolute URL as `url`, you need to set `prefixUrl` to an empty string.
210210
211211
### `signal`
212212

@@ -357,17 +357,17 @@ console.log(data.form.greeting);
357357
//=> 'Hello, world!'
358358
```
359359

360-
#### **Note:**
361-
> - If `body` is specified, then the `json` or `form` option cannot be used.
360+
> [!NOTE]
361+
> If `body` is specified, then the `json` or `form` option cannot be used.
362362
363-
#### **Note:**
364-
> - If you use this option, `got.stream()` will be read-only.
363+
> [!NOTE]
364+
> If you use this option, `got.stream()` will be read-only.
365365
366-
#### **Note:**
367-
> - Passing `body` with `GET` will throw unless the [`allowGetBody` option](#allowgetbody) is set to `true`.
366+
> [!NOTE]
367+
> Passing `body` with `GET` will throw unless the [`allowGetBody` option](#allowgetbody) is set to `true`.
368368
369-
#### **Note:**
370-
> - This option is not enumerable and will not be merged with the instance defaults.
369+
> [!NOTE]
370+
> This option is not enumerable and will not be merged with the instance defaults.
371371
372372
### `json`
373373

@@ -491,11 +491,11 @@ However, the [HTTP/2 specification](https://datatracker.ietf.org/doc/html/rfc754
491491
492492
Therefore this option has no effect when using HTTP/2.
493493

494-
#### **Note:**
495-
> - This option is only meant to interact with non-compliant servers when you have no other choice.
494+
> [!NOTE]
495+
> This option is only meant to interact with non-compliant servers when you have no other choice.
496496
497-
#### **Note:**
498-
> - The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore it's considered an [**anti-pattern**](https://en.wikipedia.org/wiki/Anti-pattern).
497+
> [!NOTE]
498+
> The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore it's considered an [**anti-pattern**](https://en.wikipedia.org/wiki/Anti-pattern).
499499
500500
### `copyPipedHeaders`
501501

@@ -630,11 +630,11 @@ const [response, buffer, json] = await Promise.all([responsePromise, bufferPromi
630630
// `json` is an object
631631
```
632632

633-
#### **Note:**
634-
> - When using streams, this option is ignored.
633+
> [!NOTE]
634+
> When using streams, this option is ignored.
635635
636-
#### **Note:**
637-
> - `'buffer'` will return the raw body bytes as a `Uint8Array`. Any modifications will also alter the result of `.text()` and `.json()`. Before overwriting it, please copy it first via `new Uint8Array(buffer)`.\
636+
> [!NOTE]
637+
> `'buffer'` will return the raw body bytes as a `Uint8Array`. Any modifications will also alter the result of `.text()` and `.json()`. Before overwriting it, please copy it first via `new Uint8Array(buffer)`.\
638638
> See https://github.com/nodejs/node/issues/27080
639639
640640
### `resolveBodyOnly`

documentation/4-pagination.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ The [RFC5988](https://datatracker.ietf.org/doc/html/rfc5988#section-5) defines h
1111
When the response has been processed, Got looks for [the reference of the `next` relation](https://datatracker.ietf.org/doc/html/rfc5988#section-6.2.2).\
1212
This way Got knows the URL it should visit afterwards. The header can look like this:
1313

14-
```
14+
```text
1515
Link: <https://api.github.com/repositories/18193978/commits?page=2>; rel="next", <https://api.github.com/repositories/18193978/commits?page=44>; rel="last"
1616
```
1717

documentation/async-stack-traces.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ await new Promise((resolve, reject) => {
4545
});
4646
```
4747
48-
```
48+
```text
4949
node:internal/process/esm_loader:74
5050
internalBinding('errors').triggerUncaughtException(
5151
^
@@ -85,7 +85,7 @@ try {
8585
}
8686
```
8787
88-
```
88+
```text
8989
TimeoutError: Timeout awaiting 'request' for 1ms
9090
at ClientRequest.<anonymous> (file:///home/szm/Desktop/got/dist/source/core/index.js:780:61)
9191
at Object.onceWrapper (node:events:514:26)
@@ -148,7 +148,7 @@ globalThis.Error = class extends Error {
148148
149149
If we replace the `bluebird` part with this, we get:
150150
151-
```
151+
```text
152152
Error: Timeout awaiting 'request' for 1ms
153153
at ClientRequest.<anonymous> (file:///home/szm/Desktop/got/dist/source/core/index.js:780:61)
154154
at Object.onceWrapper (node:events:514:26)
@@ -257,7 +257,7 @@ try {
257257
}
258258
```
259259
260-
```
260+
```text
261261
RequestError: Timeout awaiting 'request' for 100ms
262262
at ClientRequest.<anonymous> (file:///home/szm/Desktop/got/dist/source/core/index.js:780:61)
263263
at Object.onceWrapper (node:events:514:26)

documentation/cache.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ console.log(response.isFromCache);
2222

2323
Got uses [Keyv](https://github.com/lukechilds/keyv) internally to support a wide range of storage adapters. For something more scalable you could use an [official Keyv storage adapter](https://github.com/lukechilds/keyv#official-storage-adapters):
2424

25-
```
26-
$ npm install @keyv/redis
25+
```sh
26+
npm install @keyv/redis
2727
```
2828

2929
```js

readme.md

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,13 +254,11 @@ By default, Got will retry on failure. To disable this option, set [`options.ret
254254
[s3]: https://www.npmjs.com/package/superagent
255255

256256
<!-- COVERAGE -->
257-
[gc]: https://img.shields.io/coveralls/github/sindresorhus/got?color=0b9062&label
258257
[kc]: https://img.shields.io/codecov/c/github/sindresorhus/ky?color=0b9062&label
259258
[nc]: https://img.shields.io/coveralls/github/bitinn/node-fetch?color=0b9062&label
260259
[ac]: https://img.shields.io/coveralls/github/mzabriskie/axios?color=0b9062&label
261260
[sc]: https://img.shields.io/codecov/c/github/visionmedia/superagent?color=0b9062&label
262261

263-
[g4]: https://coveralls.io/github/sindresorhus/got
264262
[k4]: https://codecov.io/gh/sindresorhus/ky
265263
[n4]: https://coveralls.io/github/bitinn/node-fetch
266264
[a4]: https://coveralls.io/github/mzabriskie/axios
@@ -342,7 +340,6 @@ By default, Got will retry on failure. To disable this option, set [`options.ret
342340
[k10]: https://github.com/sindresorhus/ky
343341
[n10]: https://github.com/node-fetch/node-fetch
344342
[a10]: https://github.com/axios/axios
345-
[s10]: https://github.com/visionmedia/superagent
346343

347344
<!-- LAST COMMIT -->
348345
[glc]: https://img.shields.io/github/last-commit/sindresorhus/got?color=gray&label

source/as-promise/index.ts

Lines changed: 83 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -46,109 +46,111 @@ export default function asPromise<T>(firstRequest?: Request): RequestPromise<T>
4646

4747
globalRequest = request;
4848

49-
request.once('response', async (response: Response) => {
49+
request.once('response', (response: Response) => {
50+
void (async () => {
5051
// Parse body
51-
const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase();
52-
const isCompressed = compressedEncodings.has(contentEncoding);
52+
const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase();
53+
const isCompressed = compressedEncodings.has(contentEncoding);
5354

54-
const {options} = request;
55+
const {options} = request;
5556

56-
if (isCompressed && !options.decompress) {
57-
response.body = response.rawBody;
58-
} else {
59-
try {
60-
response.body = parseBody(response, options.responseType, options.parseJson, options.encoding);
61-
} catch (error: unknown) {
62-
// Fall back to `utf8`
57+
if (isCompressed && !options.decompress) {
58+
response.body = response.rawBody;
59+
} else {
6360
try {
64-
response.body = decodeUint8Array(response.rawBody);
65-
} catch (error) {
66-
request._beforeError(new ParseError(normalizeError(error), response));
67-
return;
68-
}
61+
response.body = parseBody(response, options.responseType, options.parseJson, options.encoding);
62+
} catch (error: unknown) {
63+
// Fall back to `utf8`
64+
try {
65+
response.body = decodeUint8Array(response.rawBody);
66+
} catch (error) {
67+
request._beforeError(new ParseError(normalizeError(error), response));
68+
return;
69+
}
6970

70-
if (isResponseOk(response)) {
71-
request._beforeError(normalizeError(error));
72-
return;
71+
if (isResponseOk(response)) {
72+
request._beforeError(normalizeError(error));
73+
return;
74+
}
7375
}
7476
}
75-
}
7677

77-
try {
78-
const hooks = options.hooks.afterResponse;
79-
80-
for (const [index, hook] of hooks.entries()) {
81-
const previousUrl = options.url ? new URL(options.url) : undefined;
82-
const previousState = previousUrl ? snapshotCrossOriginState(options) : undefined;
83-
const requestOptions = response.request.options;
84-
const responseSnapshot = response;
85-
86-
// @ts-expect-error TS doesn't notice that RequestPromise is a Promise
87-
// eslint-disable-next-line no-await-in-loop
88-
response = await requestOptions.trackStateMutations(async changedState => hook(responseSnapshot, async (updatedOptions): RequestPromise<Response> => {
89-
const preserveHooks = updatedOptions.preserveHooks ?? false;
90-
const reusesRequestOptions = updatedOptions === requestOptions;
91-
const hasExplicitBody = reusesRequestOptions
92-
? changedState.has('body') || changedState.has('json') || changedState.has('form')
93-
: (Object.hasOwn(updatedOptions, 'body') && updatedOptions.body !== undefined)
94-
|| (Object.hasOwn(updatedOptions, 'json') && updatedOptions.json !== undefined)
95-
|| (Object.hasOwn(updatedOptions, 'form') && updatedOptions.form !== undefined);
96-
97-
if (hasExplicitBody && !reusesRequestOptions) {
98-
options.clearBody();
99-
}
78+
try {
79+
const hooks = options.hooks.afterResponse;
80+
81+
for (const [index, hook] of hooks.entries()) {
82+
const previousUrl = options.url ? new URL(options.url) : undefined;
83+
const previousState = previousUrl ? snapshotCrossOriginState(options) : undefined;
84+
const requestOptions = response.request.options;
85+
const responseSnapshot = response;
86+
87+
// @ts-expect-error TS doesn't notice that RequestPromise is a Promise
88+
// eslint-disable-next-line no-await-in-loop
89+
response = await requestOptions.trackStateMutations(async changedState => hook(responseSnapshot, async (updatedOptions): RequestPromise<Response> => {
90+
const preserveHooks = updatedOptions.preserveHooks ?? false;
91+
const reusesRequestOptions = updatedOptions === requestOptions;
92+
const hasExplicitBody = reusesRequestOptions
93+
? changedState.has('body') || changedState.has('json') || changedState.has('form')
94+
: (Object.hasOwn(updatedOptions, 'body') && updatedOptions.body !== undefined)
95+
|| (Object.hasOwn(updatedOptions, 'json') && updatedOptions.json !== undefined)
96+
|| (Object.hasOwn(updatedOptions, 'form') && updatedOptions.form !== undefined);
97+
98+
if (hasExplicitBody && !reusesRequestOptions) {
99+
options.clearBody();
100+
}
100101

101-
if (!reusesRequestOptions) {
102-
options.merge(updatedOptions);
103-
}
102+
if (!reusesRequestOptions) {
103+
options.merge(updatedOptions);
104+
}
104105

105-
if (updatedOptions.url) {
106-
const nextUrl = reusesRequestOptions
107-
? options.url as URL
108-
: applyUrlOverride(options, updatedOptions.url, updatedOptions);
106+
if (updatedOptions.url) {
107+
const nextUrl = reusesRequestOptions
108+
? options.url as URL
109+
: applyUrlOverride(options, updatedOptions.url, updatedOptions);
109110

110-
if (previousUrl) {
111-
if (reusesRequestOptions && !isSameOrigin(previousUrl, nextUrl)) {
112-
options.stripUnchangedCrossOriginState(previousState!, changedState, {clearBody: !hasExplicitBody});
113-
} else {
114-
options.stripSensitiveHeaders(previousUrl, nextUrl, updatedOptions);
111+
if (previousUrl) {
112+
if (reusesRequestOptions && !isSameOrigin(previousUrl, nextUrl)) {
113+
options.stripUnchangedCrossOriginState(previousState!, changedState, {clearBody: !hasExplicitBody});
114+
} else {
115+
options.stripSensitiveHeaders(previousUrl, nextUrl, updatedOptions);
115116

116-
if (!isSameOrigin(previousUrl, nextUrl) && !hasExplicitBody) {
117-
options.clearBody();
117+
if (!isSameOrigin(previousUrl, nextUrl) && !hasExplicitBody) {
118+
options.clearBody();
119+
}
118120
}
119121
}
120122
}
121-
}
122123

123-
// Remove any further hooks for that request, because we'll call them anyway.
124-
// The loop continues. We don't want duplicates (asPromise recursion).
125-
// Unless preserveHooks is true, in which case we keep the remaining hooks.
126-
if (!preserveHooks) {
127-
options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
128-
}
124+
// Remove any further hooks for that request, because we'll call them anyway.
125+
// The loop continues. We don't want duplicates (asPromise recursion).
126+
// Unless preserveHooks is true, in which case we keep the remaining hooks.
127+
if (!preserveHooks) {
128+
options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
129+
}
129130

130-
throw new RetryError(request);
131-
}));
131+
throw new RetryError(request);
132+
}));
132133

133-
if (!(is.object(response) && is.number(response.statusCode) && 'body' in response)) {
134-
throw new TypeError('The `afterResponse` hook returned an invalid value');
134+
if (!(is.object(response) && is.number(response.statusCode) && 'body' in response)) {
135+
throw new TypeError('The `afterResponse` hook returned an invalid value');
136+
}
135137
}
138+
} catch (error: unknown) {
139+
request._beforeError(normalizeError(error));
140+
return;
136141
}
137-
} catch (error: unknown) {
138-
request._beforeError(normalizeError(error));
139-
return;
140-
}
141142

142-
globalResponse = response;
143+
globalResponse = response;
143144

144-
if (!isResponseOk(response)) {
145-
request._beforeError(new HTTPError(response));
146-
return;
147-
}
145+
if (!isResponseOk(response)) {
146+
request._beforeError(new HTTPError(response));
147+
return;
148+
}
148149

149-
request.destroy();
150-
promiseSettled = true;
151-
resolve(request.options.resolveBodyOnly ? response.body as T : response as unknown as T);
150+
request.destroy();
151+
promiseSettled = true;
152+
resolve(request.options.resolveBodyOnly ? response.body as T : response as unknown as T);
153+
})();
152154
});
153155

154156
let handledFinalError = false;
@@ -250,7 +252,7 @@ export default function asPromise<T>(firstRequest?: Request): RequestPromise<T>
250252

251253
if (responseType === 'text') {
252254
const text = decodeUint8Array(globalResponse.rawBody, options.encoding);
253-
return (isUtf8Encoding(options.encoding) ? text.replace(/^\uFEFF/u, '') : text) as T;
255+
return (isUtf8Encoding(options.encoding) ? text.replace(/^\u{FEFF}/v, '') : text) as T;
254256
}
255257

256258
return parseBody(globalResponse, responseType, options.parseJson, options.encoding);

0 commit comments

Comments
 (0)