1 | /// <reference types="node" />
|
2 | import { URL } from 'url';
|
3 | import { CancelError } from 'p-cancelable';
|
4 | import { CancelableRequest, Response, Options, NormalizedOptions, Defaults as DefaultOptions, PaginationOptions, ParseError, RequestError, CacheError, ReadError, HTTPError, MaxRedirectsError, TimeoutError, UnsupportedProtocolError, UploadError } from './as-promise';
|
5 | import Request from './core';
|
6 | declare type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
|
7 | declare type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
|
8 | /**
|
9 | Defaults for each Got instance.
|
10 | */
|
11 | export interface InstanceDefaults {
|
12 | /**
|
13 | An object containing the default options of Got.
|
14 | */
|
15 | options: DefaultOptions;
|
16 | /**
|
17 | An array of functions. You execute them directly by calling `got()`.
|
18 | They are some sort of "global hooks" - these functions are called first.
|
19 | The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
|
20 |
|
21 | @default []
|
22 | */
|
23 | handlers: HandlerFunction[];
|
24 | /**
|
25 | A read-only boolean describing whether the defaults are mutable or not.
|
26 | If set to `true`, you can update headers over time, for example, update an access token when it expires.
|
27 |
|
28 | @default false
|
29 | */
|
30 | mutableDefaults: boolean;
|
31 | _rawHandlers?: HandlerFunction[];
|
32 | }
|
33 | /**
|
34 | A Request object returned by calling Got, or any of the Got HTTP alias request functions.
|
35 | */
|
36 | export declare type GotReturn = Request | CancelableRequest;
|
37 | /**
|
38 | A function to handle options and returns a Request object.
|
39 | It acts sort of like a "global hook", and will be called before any actual request is made.
|
40 | */
|
41 | export declare type HandlerFunction = <T extends GotReturn>(options: NormalizedOptions, next: (options: NormalizedOptions) => T) => T | Promise<T>;
|
42 | /**
|
43 | The options available for `got.extend()`.
|
44 | */
|
45 | export interface ExtendOptions extends Options {
|
46 | /**
|
47 | An array of functions. You execute them directly by calling `got()`.
|
48 | They are some sort of "global hooks" - these functions are called first.
|
49 | The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
|
50 |
|
51 | @default []
|
52 | */
|
53 | handlers?: HandlerFunction[];
|
54 | /**
|
55 | A read-only boolean describing whether the defaults are mutable or not.
|
56 | If set to `true`, you can update headers over time, for example, update an access token when it expires.
|
57 |
|
58 | @default false
|
59 | */
|
60 | mutableDefaults?: boolean;
|
61 | }
|
62 | export declare type OptionsOfTextResponseBody = Merge<Options, {
|
63 | isStream?: false;
|
64 | resolveBodyOnly?: false;
|
65 | responseType?: 'text';
|
66 | }>;
|
67 | export declare type OptionsOfJSONResponseBody = Merge<Options, {
|
68 | isStream?: false;
|
69 | resolveBodyOnly?: false;
|
70 | responseType?: 'json';
|
71 | }>;
|
72 | export declare type OptionsOfBufferResponseBody = Merge<Options, {
|
73 | isStream?: false;
|
74 | resolveBodyOnly?: false;
|
75 | responseType: 'buffer';
|
76 | }>;
|
77 | export declare type OptionsOfUnknownResponseBody = Merge<Options, {
|
78 | isStream?: false;
|
79 | resolveBodyOnly?: false;
|
80 | }>;
|
81 | export declare type StrictOptions = Except<Options, 'isStream' | 'responseType' | 'resolveBodyOnly'>;
|
82 | export declare type StreamOptions = Merge<Options, {
|
83 | isStream?: true;
|
84 | }>;
|
85 | declare type ResponseBodyOnly = {
|
86 | resolveBodyOnly: true;
|
87 | };
|
88 | export declare type OptionsWithPagination<T = unknown, R = unknown> = Merge<Options, PaginationOptions<T, R>>;
|
89 | /**
|
90 | An instance of `got.paginate`.
|
91 | */
|
92 | export interface GotPaginate {
|
93 | /**
|
94 | Returns an async iterator.
|
95 |
|
96 | See pagination.options for more pagination options.
|
97 |
|
98 | @example
|
99 | ```
|
100 | (async () => {
|
101 | const countLimit = 10;
|
102 |
|
103 | const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
|
104 | pagination: {countLimit}
|
105 | });
|
106 |
|
107 | console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
|
108 |
|
109 | for await (const commitData of pagination) {
|
110 | console.log(commitData.commit.message);
|
111 | }
|
112 | })();
|
113 | ```
|
114 | */
|
115 | each: (<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>) => AsyncIterableIterator<T>) & (<T, R = unknown>(options?: OptionsWithPagination<T, R>) => AsyncIterableIterator<T>);
|
116 | /**
|
117 | Returns a Promise for an array of all results.
|
118 |
|
119 | See pagination.options for more pagination options.
|
120 |
|
121 | @example
|
122 | ```
|
123 | (async () => {
|
124 | const countLimit = 10;
|
125 |
|
126 | const results = await got.paginate.all('https://api.github.com/repos/sindresorhus/got/commits', {
|
127 | pagination: {countLimit}
|
128 | });
|
129 |
|
130 | console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
|
131 | console.log(results);
|
132 | })();
|
133 | ```
|
134 | */
|
135 | all: (<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>) => Promise<T[]>) & (<T, R = unknown>(options?: OptionsWithPagination<T, R>) => Promise<T[]>);
|
136 | /**
|
137 | Same as `GotPaginate.each`.
|
138 | */
|
139 | <T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T>;
|
140 | /**
|
141 | Same as `GotPaginate.each`.
|
142 | */
|
143 | <T, R = unknown>(options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T>;
|
144 | }
|
145 | export interface GotRequestFunction {
|
146 | (url: string | URL, options?: OptionsOfTextResponseBody): CancelableRequest<Response<string>>;
|
147 | <T>(url: string | URL, options?: OptionsOfJSONResponseBody): CancelableRequest<Response<T>>;
|
148 | (url: string | URL, options?: OptionsOfBufferResponseBody): CancelableRequest<Response<Buffer>>;
|
149 | (url: string | URL, options?: OptionsOfUnknownResponseBody): CancelableRequest<Response>;
|
150 | (options: OptionsOfTextResponseBody): CancelableRequest<Response<string>>;
|
151 | <T>(options: OptionsOfJSONResponseBody): CancelableRequest<Response<T>>;
|
152 | (options: OptionsOfBufferResponseBody): CancelableRequest<Response<Buffer>>;
|
153 | (options: OptionsOfUnknownResponseBody): CancelableRequest<Response>;
|
154 | (url: string | URL, options?: (Merge<OptionsOfTextResponseBody, ResponseBodyOnly>)): CancelableRequest<string>;
|
155 | <T>(url: string | URL, options?: (Merge<OptionsOfJSONResponseBody, ResponseBodyOnly>)): CancelableRequest<T>;
|
156 | (url: string | URL, options?: (Merge<OptionsOfBufferResponseBody, ResponseBodyOnly>)): CancelableRequest<Buffer>;
|
157 | (options: (Merge<OptionsOfTextResponseBody, ResponseBodyOnly>)): CancelableRequest<string>;
|
158 | <T>(options: (Merge<OptionsOfJSONResponseBody, ResponseBodyOnly>)): CancelableRequest<T>;
|
159 | (options: (Merge<OptionsOfBufferResponseBody, ResponseBodyOnly>)): CancelableRequest<Buffer>;
|
160 | (url: string | URL, options?: Merge<Options, {
|
161 | isStream: true;
|
162 | }>): Request;
|
163 | (options: Merge<Options, {
|
164 | isStream: true;
|
165 | }>): Request;
|
166 | (url: string | URL, options?: Options): CancelableRequest | Request;
|
167 | (options: Options): CancelableRequest | Request;
|
168 | }
|
169 | /**
|
170 | All available HTTP request methods provided by Got.
|
171 | */
|
172 | export declare type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';
|
173 | interface GotStreamFunction {
|
174 | (url: string | URL, options?: Merge<Options, {
|
175 | isStream?: true;
|
176 | }>): Request;
|
177 | (options?: Merge<Options, {
|
178 | isStream?: true;
|
179 | }>): Request;
|
180 | }
|
181 | /**
|
182 | An instance of `got.stream()`.
|
183 | */
|
184 | export declare type GotStream = GotStreamFunction & Record<HTTPAlias, GotStreamFunction>;
|
185 | /**
|
186 | An instance of `got`.
|
187 | */
|
188 | export interface Got extends Record<HTTPAlias, GotRequestFunction>, GotRequestFunction {
|
189 | /**
|
190 | Sets `options.isStream` to `true`.
|
191 |
|
192 | Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
|
193 | - request
|
194 | - response
|
195 | - redirect
|
196 | - uploadProgress
|
197 | - downloadProgress
|
198 | - error
|
199 | */
|
200 | stream: GotStream;
|
201 | /**
|
202 | Returns an async iterator.
|
203 |
|
204 | See pagination.options for more pagination options.
|
205 |
|
206 | @example
|
207 | ```
|
208 | (async () => {
|
209 | const countLimit = 10;
|
210 |
|
211 | const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
|
212 | pagination: {countLimit}
|
213 | });
|
214 |
|
215 | console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
|
216 |
|
217 | for await (const commitData of pagination) {
|
218 | console.log(commitData.commit.message);
|
219 | }
|
220 | })();
|
221 | ```
|
222 | */
|
223 | paginate: GotPaginate;
|
224 | /**
|
225 | The Got defaults used in that instance.
|
226 | */
|
227 | defaults: InstanceDefaults;
|
228 | /**
|
229 | An error to be thrown when a cache method fails.
|
230 | For example, if the database goes down or there's a filesystem error.
|
231 | */
|
232 | CacheError: typeof CacheError;
|
233 | /**
|
234 | An error to be thrown when a request fails.
|
235 | Contains a `code` property with error class code, like `ECONNREFUSED`.
|
236 | */
|
237 | RequestError: typeof RequestError;
|
238 | /**
|
239 | An error to be thrown when reading from response stream fails.
|
240 | */
|
241 | ReadError: typeof ReadError;
|
242 | /**
|
243 | An error to be thrown when server response code is 2xx, and parsing body fails.
|
244 | Includes a `response` property.
|
245 | */
|
246 | ParseError: typeof ParseError;
|
247 | /**
|
248 | An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.
|
249 | Includes a `response` property.
|
250 | */
|
251 | HTTPError: typeof HTTPError;
|
252 | /**
|
253 | An error to be thrown when the server redirects you more than ten times.
|
254 | Includes a `response` property.
|
255 | */
|
256 | MaxRedirectsError: typeof MaxRedirectsError;
|
257 | /**
|
258 | An error to be thrown when given an unsupported protocol.
|
259 | */
|
260 | UnsupportedProtocolError: typeof UnsupportedProtocolError;
|
261 | /**
|
262 | An error to be thrown when the request is aborted due to a timeout.
|
263 | Includes an `event` and `timings` property.
|
264 | */
|
265 | TimeoutError: typeof TimeoutError;
|
266 | /**
|
267 | An error to be thrown when the request body is a stream and an error occurs while reading from that stream.
|
268 | */
|
269 | UploadError: typeof UploadError;
|
270 | /**
|
271 | An error to be thrown when the request is aborted with `.cancel()`.
|
272 | */
|
273 | CancelError: typeof CancelError;
|
274 | /**
|
275 | Configure a new `got` instance with default `options`.
|
276 | The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`.
|
277 | You can access the resolved options with the `.defaults` property on the instance.
|
278 |
|
279 | Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`.
|
280 |
|
281 | It is also possible to merges many instances into a single one:
|
282 | - options are merged using `got.mergeOptions()` (including hooks),
|
283 | - handlers are stored in an array (you can access them through `instance.defaults.handlers`).
|
284 |
|
285 | @example
|
286 | ```js
|
287 | const client = got.extend({
|
288 | prefixUrl: 'https://example.com',
|
289 | headers: {
|
290 | 'x-unicorn': 'rainbow'
|
291 | }
|
292 | });
|
293 |
|
294 | client.get('demo');
|
295 |
|
296 | // HTTP Request =>
|
297 | // GET /demo HTTP/1.1
|
298 | // Host: example.com
|
299 | // x-unicorn: rainbow
|
300 | ```
|
301 | */
|
302 | extend: (...instancesOrOptions: Array<Got | ExtendOptions>) => Got;
|
303 | /**
|
304 | Merges multiple `got` instances into the parent.
|
305 | */
|
306 | mergeInstances: (parent: Got, ...instances: Got[]) => Got;
|
307 | /**
|
308 | Extends parent options.
|
309 | Avoid using [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) as it doesn't work recursively.
|
310 |
|
311 | Options are deeply merged to a new object. The value of each key is determined as follows:
|
312 |
|
313 | - If the new property is not defined, the old value is used.
|
314 | - If the new property is explicitly set to `undefined`:
|
315 | - If the parent property is a plain `object`, the parent value is deeply cloned.
|
316 | - Otherwise, `undefined` is used.
|
317 | - If the parent value is an instance of `URLSearchParams`:
|
318 | - If the new value is a `string`, an `object` or an instance of `URLSearchParams`, a new `URLSearchParams` instance is created.
|
319 | The values are merged using [`urlSearchParams.append(key, value)`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append).
|
320 | The keys defined in the new value override the keys defined in the parent value.
|
321 | - Otherwise, the only available value is `undefined`.
|
322 | - If the new property is a plain `object`:
|
323 | - If the parent property is a plain `object` too, both values are merged recursively into a new `object`.
|
324 | - Otherwise, only the new value is deeply cloned.
|
325 | - If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
|
326 | - Properties that are not enumerable, such as `context`, `body`, `json`, and `form`, will not be merged.
|
327 | - Otherwise, the new value is assigned to the key.
|
328 |
|
329 | **Note:** Only Got options are merged! Custom user options should be defined via [`options.context`](#context).
|
330 |
|
331 | @example
|
332 | ```
|
333 | const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
|
334 | const b = {headers: {cow: 'moo', wolf: ['auuu']}};
|
335 |
|
336 | {...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
|
337 | got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
|
338 | ```
|
339 | */
|
340 | mergeOptions: (...sources: Options[]) => NormalizedOptions;
|
341 | }
|
342 | export {};
|
343 |
|
\ | No newline at end of file |