Add node modules and compiled JavaScript from main (#54)

Co-authored-by: Oliver King <oking3@uncc.edu>
This commit is contained in:
github-actions[bot]
2022-06-29 15:41:55 -04:00
committed by GitHub
parent 4a983766a0
commit 52d71d28bd
6814 changed files with 2048539 additions and 2 deletions

View File

@ -0,0 +1,2 @@
import { CancelableRequest, BeforeErrorHook } from './types';
export default function createRejection(error: Error, ...beforeErrorGroups: Array<BeforeErrorHook[] | undefined>): CancelableRequest<never>;

View File

@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
function createRejection(error, ...beforeErrorGroups) {
const promise = (async () => {
if (error instanceof types_1.RequestError) {
try {
for (const hooks of beforeErrorGroups) {
if (hooks) {
for (const hook of hooks) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
}
}
catch (error_) {
error = error_;
}
}
throw error;
})();
const returnPromise = () => promise;
promise.json = returnPromise;
promise.text = returnPromise;
promise.buffer = returnPromise;
promise.on = returnPromise;
return promise;
}
exports.default = createRejection;

3
node_modules/got/dist/source/as-promise/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,3 @@
import { NormalizedOptions, CancelableRequest } from './types';
export default function asPromise<T>(normalizedOptions: NormalizedOptions): CancelableRequest<T>;
export * from './types';

175
node_modules/got/dist/source/as-promise/index.js generated vendored Normal file
View File

@ -0,0 +1,175 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const is_1 = require("@sindresorhus/is");
const PCancelable = require("p-cancelable");
const types_1 = require("./types");
const parse_body_1 = require("./parse-body");
const core_1 = require("../core");
const proxy_events_1 = require("../core/utils/proxy-events");
const get_buffer_1 = require("../core/utils/get-buffer");
const is_response_ok_1 = require("../core/utils/is-response-ok");
const proxiedRequestEvents = [
'request',
'response',
'redirect',
'uploadProgress',
'downloadProgress'
];
function asPromise(normalizedOptions) {
let globalRequest;
let globalResponse;
const emitter = new events_1.EventEmitter();
const promise = new PCancelable((resolve, reject, onCancel) => {
const makeRequest = (retryCount) => {
const request = new core_1.default(undefined, normalizedOptions);
request.retryCount = retryCount;
request._noPipe = true;
onCancel(() => request.destroy());
onCancel.shouldReject = false;
onCancel(() => reject(new types_1.CancelError(request)));
globalRequest = request;
request.once('response', async (response) => {
var _a;
response.retryCount = retryCount;
if (response.request.aborted) {
// Canceled while downloading - will throw a `CancelError` or `TimeoutError` error
return;
}
// Download body
let rawBody;
try {
rawBody = await get_buffer_1.default(request);
response.rawBody = rawBody;
}
catch (_b) {
// The same error is caught below.
// See request.once('error')
return;
}
if (request._isAboutToError) {
return;
}
// Parse body
const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase();
const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding);
const { options } = request;
if (isCompressed && !options.decompress) {
response.body = rawBody;
}
else {
try {
response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding);
}
catch (error) {
// Fallback to `utf8`
response.body = rawBody.toString();
if (is_response_ok_1.isResponseOk(response)) {
request._beforeError(error);
return;
}
}
}
try {
for (const [index, hook] of options.hooks.afterResponse.entries()) {
// @ts-expect-error TS doesn't notice that CancelableRequest is a Promise
// eslint-disable-next-line no-await-in-loop
response = await hook(response, async (updatedOptions) => {
const typedOptions = core_1.default.normalizeArguments(undefined, {
...updatedOptions,
retry: {
calculateDelay: () => 0
},
throwHttpErrors: false,
resolveBodyOnly: false
}, options);
// Remove any further hooks for that request, because we'll call them anyway.
// The loop continues. We don't want duplicates (asPromise recursion).
typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index);
for (const hook of typedOptions.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedOptions);
}
const promise = asPromise(typedOptions);
onCancel(() => {
promise.catch(() => { });
promise.cancel();
});
return promise;
});
}
}
catch (error) {
request._beforeError(new types_1.RequestError(error.message, error, request));
return;
}
globalResponse = response;
if (!is_response_ok_1.isResponseOk(response)) {
request._beforeError(new types_1.HTTPError(response));
return;
}
resolve(request.options.resolveBodyOnly ? response.body : response);
});
const onError = (error) => {
if (promise.isCanceled) {
return;
}
const { options } = request;
if (error instanceof types_1.HTTPError && !options.throwHttpErrors) {
const { response } = error;
resolve(request.options.resolveBodyOnly ? response.body : response);
return;
}
reject(error);
};
request.once('error', onError);
const previousBody = request.options.body;
request.once('retry', (newRetryCount, error) => {
var _a, _b;
if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) {
onError(error);
return;
}
makeRequest(newRetryCount);
});
proxy_events_1.default(request, emitter, proxiedRequestEvents);
};
makeRequest(0);
});
promise.on = (event, fn) => {
emitter.on(event, fn);
return promise;
};
const shortcut = (responseType) => {
const newPromise = (async () => {
// Wait until downloading has ended
await promise;
const { options } = globalResponse.request;
return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding);
})();
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise;
};
promise.json = () => {
const { headers } = globalRequest.options;
if (!globalRequest.writableFinished && headers.accept === undefined) {
headers.accept = 'application/json';
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}
exports.default = asPromise;
__exportStar(require("./types"), exports);

View File

@ -0,0 +1,3 @@
import { NormalizedOptions, Defaults } from './types';
declare const normalizeArguments: (options: NormalizedOptions, defaults?: Defaults | undefined) => NormalizedOptions;
export default normalizeArguments;

View File

@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
const normalizeArguments = (options, defaults) => {
if (is_1.default.null_(options.encoding)) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding);
is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly);
is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting);
is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream);
is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType);
// `options.responseType`
if (options.responseType === undefined) {
options.responseType = 'text';
}
// `options.retry`
const { retry } = options;
if (defaults) {
options.retry = { ...defaults.retry };
}
else {
options.retry = {
calculateDelay: retryObject => retryObject.computedValue,
limit: 0,
methods: [],
statusCodes: [],
errorCodes: [],
maxRetryAfter: undefined
};
}
if (is_1.default.object(retry)) {
options.retry = {
...options.retry,
...retry
};
options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];
options.retry.statusCodes = [...new Set(options.retry.statusCodes)];
options.retry.errorCodes = [...new Set(options.retry.errorCodes)];
}
else if (is_1.default.number(retry)) {
options.retry.limit = retry;
}
if (is_1.default.undefined(options.retry.maxRetryAfter)) {
options.retry.maxRetryAfter = Math.min(
// TypeScript is not smart enough to handle `.filter(x => is.number(x))`.
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
...[options.timeout.request, options.timeout.connect].filter(is_1.default.number));
}
// `options.pagination`
if (is_1.default.object(options.pagination)) {
if (defaults) {
options.pagination = {
...defaults.pagination,
...options.pagination
};
}
const { pagination } = options;
if (!is_1.default.function_(pagination.transform)) {
throw new Error('`options.pagination.transform` must be implemented');
}
if (!is_1.default.function_(pagination.shouldContinue)) {
throw new Error('`options.pagination.shouldContinue` must be implemented');
}
if (!is_1.default.function_(pagination.filter)) {
throw new TypeError('`options.pagination.filter` must be implemented');
}
if (!is_1.default.function_(pagination.paginate)) {
throw new Error('`options.pagination.paginate` must be implemented');
}
}
// JSON mode
if (options.responseType === 'json' && options.headers.accept === undefined) {
options.headers.accept = 'application/json';
}
return options;
};
exports.default = normalizeArguments;

View File

@ -0,0 +1,3 @@
import { ResponseType, Response, ParseJsonFunction } from './types';
declare const parseBody: (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex" | undefined) => unknown;
export default parseBody;

25
node_modules/got/dist/source/as-promise/parse-body.js generated vendored Normal file
View File

@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const parseBody = (response, responseType, parseJson, encoding) => {
const { rawBody } = response;
try {
if (responseType === 'text') {
return rawBody.toString(encoding);
}
if (responseType === 'json') {
return rawBody.length === 0 ? '' : parseJson(rawBody.toString());
}
if (responseType === 'buffer') {
return rawBody;
}
throw new types_1.ParseError({
message: `Unknown body type '${responseType}'`,
name: 'Error'
}, response);
}
catch (error) {
throw new types_1.ParseError(error, response);
}
};
exports.default = parseBody;

256
node_modules/got/dist/source/as-promise/types.d.ts generated vendored Normal file
View File

@ -0,0 +1,256 @@
/// <reference types="node" />
import PCancelable = require('p-cancelable');
import Request, { Options, Response, RequestError, RequestEvents } from '../core';
/**
All parsing methods supported by Got.
*/
export declare type ResponseType = 'json' | 'buffer' | 'text';
export interface PaginationOptions<T, R> {
/**
All options accepted by `got.paginate()`.
*/
pagination?: {
/**
A function that transform [`Response`](#response) into an array of items.
This is where you should do the parsing.
@default response => JSON.parse(response.body)
*/
transform?: (response: Response<R>) => Promise<T[]> | T[];
/**
Checks whether the item should be emitted or not.
@default (item, allItems, currentItems) => true
*/
filter?: (item: T, allItems: T[], currentItems: T[]) => boolean;
/**
The function takes three arguments:
- `response` - The current response object.
- `allItems` - An array of the emitted items.
- `currentItems` - Items from the current response.
It should return an object representing Got options pointing to the next page.
The options are merged automatically with the previous request, therefore the options returned `pagination.paginate(...)` must reflect changes only.
If there are no more pages, `false` should be returned.
@example
```
const got = require('got');
(async () => {
const limit = 10;
const items = got.paginate('https://example.com/items', {
searchParams: {
limit,
offset: 0
},
pagination: {
paginate: (response, allItems, currentItems) => {
const previousSearchParams = response.request.options.searchParams;
const previousOffset = previousSearchParams.get('offset');
if (currentItems.length < limit) {
return false;
}
return {
searchParams: {
...previousSearchParams,
offset: Number(previousOffset) + limit,
}
};
}
}
});
console.log('Items from all pages:', items);
})();
```
*/
paginate?: (response: Response<R>, allItems: T[], currentItems: T[]) => Options | false;
/**
Checks whether the pagination should continue.
For example, if you need to stop **before** emitting an entry with some flag, you should use `(item, allItems, currentItems) => !item.flag`.
If you want to stop **after** emitting the entry, you should use `(item, allItems, currentItems) => allItems.some(entry => entry.flag)` instead.
@default (item, allItems, currentItems) => true
*/
shouldContinue?: (item: T, allItems: T[], currentItems: T[]) => boolean;
/**
The maximum amount of items that should be emitted.
@default Infinity
*/
countLimit?: number;
/**
Milliseconds to wait before the next request is triggered.
@default 0
*/
backoff?: number;
/**
The maximum amount of request that should be triggered.
Retries on failure are not counted towards this limit.
For example, it can be helpful during development to avoid an infinite number of requests.
@default 10000
*/
requestLimit?: number;
/**
Defines how the parameter `allItems` in pagination.paginate, pagination.filter and pagination.shouldContinue is managed.
When set to `false`, the parameter `allItems` is always an empty array.
This option can be helpful to save on memory usage when working with a large dataset.
*/
stackAllItems?: boolean;
};
}
export declare type AfterResponseHook = (response: Response, retryWithMergedOptions: (options: Options) => CancelableRequest<Response>) => Response | CancelableRequest<Response> | Promise<Response | CancelableRequest<Response>>;
export declare namespace PromiseOnly {
interface Hooks {
/**
Called with [response object](#response) and a retry function.
Calling the retry function will trigger `beforeRetry` hooks.
Each function should return the response.
This is especially useful when you want to refresh an access token.
__Note__: When using streams, this hook is ignored.
@example
```
const got = require('got');
const instance = got.extend({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) { // Unauthorized
const updatedOptions = {
headers: {
token: getNewToken() // Refresh the access token
}
};
// Save for further requests
instance.defaults.options = got.mergeOptions(instance.defaults.options, updatedOptions);
// Make a new retry
return retryWithMergedOptions(updatedOptions);
}
// No changes otherwise
return response;
}
],
beforeRetry: [
(options, error, retryCount) => {
// This will be called on `retryWithMergedOptions(...)`
}
]
},
mutableDefaults: true
});
```
*/
afterResponse?: AfterResponseHook[];
}
interface Options extends PaginationOptions<unknown, unknown> {
/**
The parsing method.
The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
__Note__: When using streams, this option is ignored.
@example
```
(async () => {
const responsePromise = got(url);
const bufferPromise = responsePromise.buffer();
const jsonPromise = responsePromise.json();
const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
// `response` is an instance of Got Response
// `buffer` is an instance of Buffer
// `json` is an object
})();
```
@example
```
// This
const body = await got(url).json();
// is semantically the same as this
const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
```
*/
responseType?: ResponseType;
/**
When set to `true` the promise will return the Response body instead of the Response object.
@default false
*/
resolveBodyOnly?: boolean;
/**
Returns a `Stream` instead of a `Promise`.
This is equivalent to calling `got.stream(url, options?)`.
@default false
*/
isStream?: boolean;
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
Don't set this option to `null`.
__Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
@default 'utf-8'
*/
encoding?: BufferEncoding;
}
interface NormalizedOptions {
responseType: ResponseType;
resolveBodyOnly: boolean;
isStream: boolean;
encoding?: BufferEncoding;
pagination?: Required<PaginationOptions<unknown, unknown>['pagination']>;
}
interface Defaults {
responseType: ResponseType;
resolveBodyOnly: boolean;
isStream: boolean;
pagination?: Required<PaginationOptions<unknown, unknown>['pagination']>;
}
type HookEvent = 'afterResponse';
}
/**
An error to be thrown when server response code is 2xx, and parsing body fails.
Includes a `response` property.
*/
export declare class ParseError extends RequestError {
readonly response: Response;
constructor(error: Error, response: Response);
}
/**
An error to be thrown when the request is aborted with `.cancel()`.
*/
export declare class CancelError extends RequestError {
readonly response: Response;
constructor(request: Request);
get isCanceled(): boolean;
}
export interface CancelableRequest<T extends Response | Response['body'] = Response['body']> extends PCancelable<T>, RequestEvents<CancelableRequest<T>> {
json: <ReturnType>() => CancelableRequest<ReturnType>;
buffer: () => CancelableRequest<Buffer>;
text: () => CancelableRequest<string>;
}
export * from '../core';

42
node_modules/got/dist/source/as-promise/types.js generated vendored Normal file
View File

@ -0,0 +1,42 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancelError = exports.ParseError = void 0;
const core_1 = require("../core");
/**
An error to be thrown when server response code is 2xx, and parsing body fails.
Includes a `response` property.
*/
class ParseError extends core_1.RequestError {
constructor(error, response) {
const { options } = response.request;
super(`${error.message} in "${options.url.toString()}"`, error, response.request);
this.name = 'ParseError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code;
}
}
exports.ParseError = ParseError;
/**
An error to be thrown when the request is aborted with `.cancel()`.
*/
class CancelError extends core_1.RequestError {
constructor(request) {
super('Promise was canceled', {}, request);
this.name = 'CancelError';
this.code = 'ERR_CANCELED';
}
get isCanceled() {
return true;
}
}
exports.CancelError = CancelError;
__exportStar(require("../core"), exports);

View File

@ -0,0 +1,5 @@
import { RetryFunction } from '.';
declare type Returns<T extends (...args: any) => unknown, V> = (...args: Parameters<T>) => V;
export declare const retryAfterStatusCodes: ReadonlySet<number>;
declare const calculateRetryDelay: Returns<RetryFunction, number>;
export default calculateRetryDelay;

View File

@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.retryAfterStatusCodes = void 0;
exports.retryAfterStatusCodes = new Set([413, 429, 503]);
const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => {
if (attemptCount > retryOptions.limit) {
return 0;
}
const hasMethod = retryOptions.methods.includes(error.options.method);
const hasErrorCode = retryOptions.errorCodes.includes(error.code);
const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode);
if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {
return 0;
}
if (error.response) {
if (retryAfter) {
if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) {
return 0;
}
return retryAfter;
}
if (error.response.statusCode === 413) {
return 0;
}
}
const noise = Math.random() * 100;
return ((2 ** (attemptCount - 1)) * 1000) + noise;
};
exports.default = calculateRetryDelay;

1124
node_modules/got/dist/source/core/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1505
node_modules/got/dist/source/core/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
export declare type DnsLookupIpVersion = 'auto' | 'ipv4' | 'ipv6';
declare type DnsIpFamily = 0 | 4 | 6;
export declare const isDnsLookupIpVersion: (value: any) => boolean;
export declare const dnsLookupIpVersionToFamily: (dnsLookupIpVersion: DnsLookupIpVersion) => DnsIpFamily;
export {};

View File

@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0;
const conversionTable = {
auto: 0,
ipv4: 4,
ipv6: 6
};
exports.isDnsLookupIpVersion = (value) => {
return value in conversionTable;
};
exports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => {
if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) {
return conversionTable[dnsLookupIpVersion];
}
throw new Error('Invalid DNS lookup IP version');
};

View File

@ -0,0 +1,3 @@
import { ClientRequestArgs } from 'http';
declare const _default: (body: unknown, headers: ClientRequestArgs['headers']) => Promise<number | undefined>;
export default _default;

View File

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const util_1 = require("util");
const is_1 = require("@sindresorhus/is");
const is_form_data_1 = require("./is-form-data");
const statAsync = util_1.promisify(fs_1.stat);
exports.default = async (body, headers) => {
if (headers && 'content-length' in headers) {
return Number(headers['content-length']);
}
if (!body) {
return 0;
}
if (is_1.default.string(body)) {
return Buffer.byteLength(body);
}
if (is_1.default.buffer(body)) {
return body.length;
}
if (is_form_data_1.default(body)) {
return util_1.promisify(body.getLength.bind(body))();
}
if (body instanceof fs_1.ReadStream) {
const { size } = await statAsync(body.path);
if (size === 0) {
return undefined;
}
return size;
}
return undefined;
};

View File

@ -0,0 +1,4 @@
/// <reference types="node" />
import { Readable } from 'stream';
declare const getBuffer: (stream: Readable) => Promise<Buffer>;
export default getBuffer;

16
node_modules/got/dist/source/core/utils/get-buffer.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// TODO: Update https://github.com/sindresorhus/get-stream
const getBuffer = async (stream) => {
const chunks = [];
let length = 0;
for await (const chunk of stream) {
chunks.push(chunk);
length += Buffer.byteLength(chunk);
}
if (Buffer.isBuffer(chunks[0])) {
return Buffer.concat(chunks, length);
}
return Buffer.from(chunks.join(''));
};
exports.default = getBuffer;

View File

@ -0,0 +1,8 @@
/// <reference types="node" />
import { Readable } from 'stream';
interface FormData extends Readable {
getBoundary: () => string;
getLength: (callback: (error: Error | null, length: number) => void) => void;
}
declare const _default: (body: unknown) => body is FormData;
export default _default;

View File

@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
exports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary);

View File

@ -0,0 +1,2 @@
import { Response } from '..';
export declare const isResponseOk: (response: Response) => boolean;

View File

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isResponseOk = void 0;
exports.isResponseOk = (response) => {
const { statusCode } = response;
const limitStatusCode = response.request.options.followRedirect ? 299 : 399;
return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
};

View File

@ -0,0 +1,14 @@
import { URL } from 'url';
export interface URLOptions {
href?: string;
protocol?: string;
host?: string;
hostname?: string;
port?: string | number;
pathname?: string;
search?: string;
searchParams?: unknown;
path?: string;
}
declare const _default: (origin: string, options: URLOptions) => URL;
export default _default;

View File

@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* istanbul ignore file: deprecated */
const url_1 = require("url");
const keys = [
'protocol',
'host',
'hostname',
'port',
'pathname',
'search'
];
exports.default = (origin, options) => {
var _a, _b;
if (options.path) {
if (options.pathname) {
throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.');
}
if (options.search) {
throw new TypeError('Parameters `path` and `search` are mutually exclusive.');
}
if (options.searchParams) {
throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.');
}
}
if (options.search && options.searchParams) {
throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.');
}
if (!origin) {
if (!options.protocol) {
throw new TypeError('No URL protocol specified');
}
origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`;
}
const url = new url_1.URL(origin);
if (options.path) {
const searchIndex = options.path.indexOf('?');
if (searchIndex === -1) {
options.pathname = options.path;
}
else {
options.pathname = options.path.slice(0, searchIndex);
options.search = options.path.slice(searchIndex + 1);
}
delete options.path;
}
for (const key of keys) {
if (options[key]) {
url[key] = options[key].toString();
}
}
return url;
};

View File

@ -0,0 +1,3 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
export default function (from: EventEmitter, to: EventEmitter, events: string[]): () => void;

View File

@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function default_1(from, to, events) {
const fns = {};
for (const event of events) {
fns[event] = (...args) => {
to.emit(event, ...args);
};
from.on(event, fns[event]);
}
return () => {
for (const event of events) {
from.off(event, fns[event]);
}
};
}
exports.default = default_1;

29
node_modules/got/dist/source/core/utils/timed-out.d.ts generated vendored Normal file
View File

@ -0,0 +1,29 @@
import { ClientRequest } from 'http';
declare const reentry: unique symbol;
interface TimedOutOptions {
host?: string;
hostname?: string;
protocol?: string;
}
export interface Delays {
lookup?: number;
connect?: number;
secureConnect?: number;
socket?: number;
response?: number;
send?: number;
request?: number;
}
export declare type ErrorCode = 'ETIMEDOUT' | 'ECONNRESET' | 'EADDRINUSE' | 'ECONNREFUSED' | 'EPIPE' | 'ENOTFOUND' | 'ENETUNREACH' | 'EAI_AGAIN';
export declare class TimeoutError extends Error {
event: string;
code: ErrorCode;
constructor(threshold: number, event: string);
}
declare const _default: (request: ClientRequest, delays: Delays, options: TimedOutOptions) => () => void;
export default _default;
declare module 'http' {
interface ClientRequest {
[reentry]: boolean;
}
}

121
node_modules/got/dist/source/core/utils/timed-out.js generated vendored Normal file
View File

@ -0,0 +1,121 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimeoutError = void 0;
const net = require("net");
const unhandle_1 = require("./unhandle");
const reentry = Symbol('reentry');
const noop = () => { };
class TimeoutError extends Error {
constructor(threshold, event) {
super(`Timeout awaiting '${event}' for ${threshold}ms`);
this.event = event;
this.name = 'TimeoutError';
this.code = 'ETIMEDOUT';
}
}
exports.TimeoutError = TimeoutError;
exports.default = (request, delays, options) => {
if (reentry in request) {
return noop;
}
request[reentry] = true;
const cancelers = [];
const { once, unhandleAll } = unhandle_1.default();
const addTimeout = (delay, callback, event) => {
var _a;
const timeout = setTimeout(callback, delay, delay, event);
(_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout);
const cancel = () => {
clearTimeout(timeout);
};
cancelers.push(cancel);
return cancel;
};
const { host, hostname } = options;
const timeoutHandler = (delay, event) => {
request.destroy(new TimeoutError(delay, event));
};
const cancelTimeouts = () => {
for (const cancel of cancelers) {
cancel();
}
unhandleAll();
};
request.once('error', error => {
cancelTimeouts();
// Save original behavior
/* istanbul ignore next */
if (request.listenerCount('error') === 0) {
throw error;
}
});
request.once('close', cancelTimeouts);
once(request, 'response', (response) => {
once(response, 'end', cancelTimeouts);
});
if (typeof delays.request !== 'undefined') {
addTimeout(delays.request, timeoutHandler, 'request');
}
if (typeof delays.socket !== 'undefined') {
const socketTimeoutHandler = () => {
timeoutHandler(delays.socket, 'socket');
};
request.setTimeout(delays.socket, socketTimeoutHandler);
// `request.setTimeout(0)` causes a memory leak.
// We can just remove the listener and forget about the timer - it's unreffed.
// See https://github.com/sindresorhus/got/issues/690
cancelers.push(() => {
request.removeListener('timeout', socketTimeoutHandler);
});
}
once(request, 'socket', (socket) => {
var _a;
const { socketPath } = request;
/* istanbul ignore next: hard to test */
if (socket.connecting) {
const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0);
if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') {
const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
once(socket, 'lookup', cancelTimeout);
}
if (typeof delays.connect !== 'undefined') {
const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');
if (hasPath) {
once(socket, 'connect', timeConnect());
}
else {
once(socket, 'lookup', (error) => {
if (error === null) {
once(socket, 'connect', timeConnect());
}
});
}
}
if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') {
once(socket, 'connect', () => {
const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');
once(socket, 'secureConnect', cancelTimeout);
});
}
}
if (typeof delays.send !== 'undefined') {
const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');
/* istanbul ignore next: hard to test */
if (socket.connecting) {
once(socket, 'connect', () => {
once(request, 'upload-complete', timeRequest());
});
}
else {
once(request, 'upload-complete', timeRequest());
}
}
});
if (typeof delays.response !== 'undefined') {
once(request, 'upload-complete', () => {
const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');
once(request, 'response', cancelTimeout);
});
}
return cancelTimeouts;
};

11
node_modules/got/dist/source/core/utils/unhandle.d.ts generated vendored Normal file
View File

@ -0,0 +1,11 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
declare type Origin = EventEmitter;
declare type Event = string | symbol;
declare type Fn = (...args: any[]) => void;
interface Unhandler {
once: (origin: Origin, event: Event, fn: Fn) => void;
unhandleAll: () => void;
}
declare const _default: () => Unhandler;
export default _default;

22
node_modules/got/dist/source/core/utils/unhandle.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// When attaching listeners, it's very easy to forget about them.
// Especially if you do error handling and set timeouts.
// So instead of checking if it's proper to throw an error on every timeout ever,
// use this simple tool which will remove all listeners you have attached.
exports.default = () => {
const handlers = [];
return {
once(origin, event, fn) {
origin.once(event, fn);
handlers.push({ origin, event, fn });
},
unhandleAll() {
for (const handler of handlers) {
const { origin, event, fn } = handler;
origin.removeListener(event, fn);
}
handlers.length = 0;
}
};
};

View File

@ -0,0 +1,15 @@
import { URL, UrlWithStringQuery } from 'url';
export interface LegacyUrlOptions {
protocol: string;
hostname: string;
host: string;
hash: string | null;
search: string | null;
pathname: string;
href: string;
path: string;
port?: number;
auth?: string;
}
declare const _default: (url: URL | UrlWithStringQuery) => LegacyUrlOptions;
export default _default;

View File

@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
exports.default = (url) => {
// Cast to URL
url = url;
const options = {
protocol: url.protocol,
hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,
host: url.host,
hash: url.hash,
search: url.search,
pathname: url.pathname,
href: url.href,
path: `${url.pathname || ''}${url.search || ''}`
};
if (is_1.default.string(url.port) && url.port.length > 0) {
options.port = Number(url.port);
}
if (url.username || url.password) {
options.auth = `${url.username || ''}:${url.password || ''}`;
}
return options;
};

View File

@ -0,0 +1,8 @@
export default class WeakableMap<K, V> {
weakMap: WeakMap<Record<string, unknown>, V>;
map: Map<K, V>;
constructor();
set(key: K, value: V): void;
get(key: K): V | undefined;
has(key: K): boolean;
}

View File

@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class WeakableMap {
constructor() {
this.weakMap = new WeakMap();
this.map = new Map();
}
set(key, value) {
if (typeof key === 'object') {
this.weakMap.set(key, value);
}
else {
this.map.set(key, value);
}
}
get(key) {
if (typeof key === 'object') {
return this.weakMap.get(key);
}
return this.map.get(key);
}
has(key) {
if (typeof key === 'object') {
return this.weakMap.has(key);
}
return this.map.has(key);
}
}
exports.default = WeakableMap;

5
node_modules/got/dist/source/create.d.ts generated vendored Normal file
View File

@ -0,0 +1,5 @@
import { Got, HandlerFunction, InstanceDefaults } from './types';
export declare const defaultHandler: HandlerFunction;
declare const create: (defaults: InstanceDefaults) => Got;
export default create;
export * from './types';

240
node_modules/got/dist/source/create.js generated vendored Normal file
View File

@ -0,0 +1,240 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultHandler = void 0;
const is_1 = require("@sindresorhus/is");
const as_promise_1 = require("./as-promise");
const create_rejection_1 = require("./as-promise/create-rejection");
const core_1 = require("./core");
const deep_freeze_1 = require("./utils/deep-freeze");
const errors = {
RequestError: as_promise_1.RequestError,
CacheError: as_promise_1.CacheError,
ReadError: as_promise_1.ReadError,
HTTPError: as_promise_1.HTTPError,
MaxRedirectsError: as_promise_1.MaxRedirectsError,
TimeoutError: as_promise_1.TimeoutError,
ParseError: as_promise_1.ParseError,
CancelError: as_promise_1.CancelError,
UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError,
UploadError: as_promise_1.UploadError
};
// The `delay` package weighs 10KB (!)
const delay = async (ms) => new Promise(resolve => {
setTimeout(resolve, ms);
});
const { normalizeArguments } = core_1.default;
const mergeOptions = (...sources) => {
let mergedOptions;
for (const source of sources) {
mergedOptions = normalizeArguments(undefined, source, mergedOptions);
}
return mergedOptions;
};
const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options);
const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults);
const aliases = [
'get',
'post',
'put',
'patch',
'head',
'delete'
];
exports.defaultHandler = (options, next) => next(options);
const callInitHooks = (hooks, options) => {
if (hooks) {
for (const hook of hooks) {
hook(options);
}
}
};
const create = (defaults) => {
// Proxy properties from next handlers
defaults._rawHandlers = defaults.handlers;
defaults.handlers = defaults.handlers.map(fn => ((options, next) => {
// This will be assigned by assigning result
let root;
const result = fn(options, newOptions => {
root = next(newOptions);
return root;
});
if (result !== root && !options.isStream && root) {
const typedResult = result;
const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult;
Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root));
Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root));
// These should point to the new promise
// eslint-disable-next-line promise/prefer-await-to-then
typedResult.then = promiseThen;
typedResult.catch = promiseCatch;
typedResult.finally = promiseFianlly;
}
return result;
}));
// Got interface
const got = ((url, options = {}, _defaults) => {
var _a, _b;
let iteration = 0;
const iterateHandlers = (newOptions) => {
return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers);
};
// TODO: Remove this in Got 12.
if (is_1.default.plainObject(url)) {
const mergedOptions = {
...url,
...options
};
core_1.setNonEnumerableProperties([url, options], mergedOptions);
options = mergedOptions;
url = undefined;
}
try {
// Call `init` hooks
let initHookError;
try {
callInitHooks(defaults.options.hooks.init, options);
callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options);
}
catch (error) {
initHookError = error;
}
// Normalize options & call handlers
const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options);
normalizedOptions[core_1.kIsNormalizedAlready] = true;
if (initHookError) {
throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions);
}
return iterateHandlers(normalizedOptions);
}
catch (error) {
if (options.isStream) {
throw error;
}
else {
return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError);
}
}
});
got.extend = (...instancesOrOptions) => {
const optionsArray = [defaults.options];
let handlers = [...defaults._rawHandlers];
let isMutableDefaults;
for (const value of instancesOrOptions) {
if (isGotInstance(value)) {
optionsArray.push(value.defaults.options);
handlers.push(...value.defaults._rawHandlers);
isMutableDefaults = value.defaults.mutableDefaults;
}
else {
optionsArray.push(value);
if ('handlers' in value) {
handlers.push(...value.handlers);
}
isMutableDefaults = value.mutableDefaults;
}
}
handlers = handlers.filter(handler => handler !== exports.defaultHandler);
if (handlers.length === 0) {
handlers.push(exports.defaultHandler);
}
return create({
options: mergeOptions(...optionsArray),
handlers,
mutableDefaults: Boolean(isMutableDefaults)
});
};
// Pagination
const paginateEach = (async function* (url, options) {
// TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4.
// Error: Argument of type 'Merge<Options, PaginationOptions<T, R>> | undefined' is not assignable to parameter of type 'Options | undefined'.
// @ts-expect-error
let normalizedOptions = normalizeArguments(url, options, defaults.options);
normalizedOptions.resolveBodyOnly = false;
const pagination = normalizedOptions.pagination;
if (!is_1.default.object(pagination)) {
throw new TypeError('`options.pagination` must be implemented');
}
const all = [];
let { countLimit } = pagination;
let numberOfRequests = 0;
while (numberOfRequests < pagination.requestLimit) {
if (numberOfRequests !== 0) {
// eslint-disable-next-line no-await-in-loop
await delay(pagination.backoff);
}
// @ts-expect-error FIXME!
// TODO: Throw when result is not an instance of Response
// eslint-disable-next-line no-await-in-loop
const result = (await got(undefined, undefined, normalizedOptions));
// eslint-disable-next-line no-await-in-loop
const parsed = await pagination.transform(result);
const current = [];
for (const item of parsed) {
if (pagination.filter(item, all, current)) {
if (!pagination.shouldContinue(item, all, current)) {
return;
}
yield item;
if (pagination.stackAllItems) {
all.push(item);
}
current.push(item);
if (--countLimit <= 0) {
return;
}
}
}
const optionsToMerge = pagination.paginate(result, all, current);
if (optionsToMerge === false) {
return;
}
if (optionsToMerge === result.request.options) {
normalizedOptions = result.request.options;
}
else if (optionsToMerge !== undefined) {
normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions);
}
numberOfRequests++;
}
});
got.paginate = paginateEach;
got.paginate.all = (async (url, options) => {
const results = [];
for await (const item of paginateEach(url, options)) {
results.push(item);
}
return results;
});
// For those who like very descriptive names
got.paginate.each = paginateEach;
// Stream API
got.stream = ((url, options) => got(url, { ...options, isStream: true }));
// Shortcuts
for (const method of aliases) {
got[method] = ((url, options) => got(url, { ...options, method }));
got.stream[method] = ((url, options) => {
return got(url, { ...options, method, isStream: true });
});
}
Object.assign(got, errors);
Object.defineProperty(got, 'defaults', {
value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults),
writable: defaults.mutableDefaults,
configurable: defaults.mutableDefaults,
enumerable: true
});
got.mergeOptions = mergeOptions;
return got;
};
exports.default = create;
__exportStar(require("./types"), exports);

4
node_modules/got/dist/source/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,4 @@
declare const got: import("./types").Got;
export default got;
export * from './create';
export * from './as-promise';

132
node_modules/got/dist/source/index.js generated vendored Normal file
View File

@ -0,0 +1,132 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const create_1 = require("./create");
const defaults = {
options: {
method: 'GET',
retry: {
limit: 2,
methods: [
'GET',
'PUT',
'HEAD',
'DELETE',
'OPTIONS',
'TRACE'
],
statusCodes: [
408,
413,
429,
500,
502,
503,
504,
521,
522,
524
],
errorCodes: [
'ETIMEDOUT',
'ECONNRESET',
'EADDRINUSE',
'ECONNREFUSED',
'EPIPE',
'ENOTFOUND',
'ENETUNREACH',
'EAI_AGAIN'
],
maxRetryAfter: undefined,
calculateDelay: ({ computedValue }) => computedValue
},
timeout: {},
headers: {
'user-agent': 'got (https://github.com/sindresorhus/got)'
},
hooks: {
init: [],
beforeRequest: [],
beforeRedirect: [],
beforeRetry: [],
beforeError: [],
afterResponse: []
},
cache: undefined,
dnsCache: undefined,
decompress: true,
throwHttpErrors: true,
followRedirect: true,
isStream: false,
responseType: 'text',
resolveBodyOnly: false,
maxRedirects: 10,
prefixUrl: '',
methodRewriting: true,
ignoreInvalidCookies: false,
context: {},
// TODO: Set this to `true` when Got 12 gets released
http2: false,
allowGetBody: false,
https: undefined,
pagination: {
transform: (response) => {
if (response.request.options.responseType === 'json') {
return response.body;
}
return JSON.parse(response.body);
},
paginate: response => {
if (!Reflect.has(response.headers, 'link')) {
return false;
}
const items = response.headers.link.split(',');
let next;
for (const item of items) {
const parsed = item.split(';');
if (parsed[1].includes('next')) {
next = parsed[0].trimStart().trim();
next = next.slice(1, -1);
break;
}
}
if (next) {
const options = {
url: new url_1.URL(next)
};
return options;
}
return false;
},
filter: () => true,
shouldContinue: () => true,
countLimit: Infinity,
backoff: 0,
requestLimit: 10000,
stackAllItems: true
},
parseJson: (text) => JSON.parse(text),
stringifyJson: (object) => JSON.stringify(object),
cacheOptions: {}
},
handlers: [create_1.defaultHandler],
mutableDefaults: false
};
const got = create_1.default(defaults);
exports.default = got;
// For CommonJS default export support
module.exports = got;
module.exports.default = got;
module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267
__exportStar(require("./create"), exports);
__exportStar(require("./as-promise"), exports);

344
node_modules/got/dist/source/types.d.ts generated vendored Normal file
View File

@ -0,0 +1,344 @@
/// <reference types="node" />
import { URL } from 'url';
import { CancelError } from 'p-cancelable';
import { CancelableRequest, Response, Options, NormalizedOptions, Defaults as DefaultOptions, PaginationOptions, ParseError, RequestError, CacheError, ReadError, HTTPError, MaxRedirectsError, TimeoutError, UnsupportedProtocolError, UploadError } from './as-promise';
import Request from './core';
declare type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
declare type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
/**
Defaults for each Got instance.
*/
export interface InstanceDefaults {
/**
An object containing the default options of Got.
*/
options: DefaultOptions;
/**
An array of functions. You execute them directly by calling `got()`.
They are some sort of "global hooks" - these functions are called first.
The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
@default []
*/
handlers: HandlerFunction[];
/**
A read-only boolean describing whether the defaults are mutable or not.
If set to `true`, you can update headers over time, for example, update an access token when it expires.
@default false
*/
mutableDefaults: boolean;
_rawHandlers?: HandlerFunction[];
}
/**
A Request object returned by calling Got, or any of the Got HTTP alias request functions.
*/
export declare type GotReturn = Request | CancelableRequest;
/**
A function to handle options and returns a Request object.
It acts sort of like a "global hook", and will be called before any actual request is made.
*/
export declare type HandlerFunction = <T extends GotReturn>(options: NormalizedOptions, next: (options: NormalizedOptions) => T) => T | Promise<T>;
/**
The options available for `got.extend()`.
*/
export interface ExtendOptions extends Options {
/**
An array of functions. You execute them directly by calling `got()`.
They are some sort of "global hooks" - these functions are called first.
The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
@default []
*/
handlers?: HandlerFunction[];
/**
A read-only boolean describing whether the defaults are mutable or not.
If set to `true`, you can update headers over time, for example, update an access token when it expires.
@default false
*/
mutableDefaults?: boolean;
}
export declare type OptionsOfTextResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType?: 'text';
}>;
export declare type OptionsOfJSONResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType?: 'json';
}>;
export declare type OptionsOfBufferResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType: 'buffer';
}>;
export declare type OptionsOfUnknownResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
}>;
export declare type StrictOptions = Except<Options, 'isStream' | 'responseType' | 'resolveBodyOnly'>;
export declare type StreamOptions = Merge<Options, {
isStream?: true;
}>;
declare type ResponseBodyOnly = {
resolveBodyOnly: true;
};
export declare type OptionsWithPagination<T = unknown, R = unknown> = Merge<Options, PaginationOptions<T, R>>;
/**
An instance of `got.paginate`.
*/
export interface GotPaginate {
/**
Same as `GotPaginate.each`.
*/
<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T>;
/**
Same as `GotPaginate.each`.
*/
<T, R = unknown>(options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T>;
/**
Returns an async iterator.
See pagination.options for more pagination options.
@example
```
(async () => {
const countLimit = 10;
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
pagination: {countLimit}
});
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
})();
```
*/
each: (<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>) => AsyncIterableIterator<T>) & (<T, R = unknown>(options?: OptionsWithPagination<T, R>) => AsyncIterableIterator<T>);
/**
Returns a Promise for an array of all results.
See pagination.options for more pagination options.
@example
```
(async () => {
const countLimit = 10;
const results = await got.paginate.all('https://api.github.com/repos/sindresorhus/got/commits', {
pagination: {countLimit}
});
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
console.log(results);
})();
```
*/
all: (<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>) => Promise<T[]>) & (<T, R = unknown>(options?: OptionsWithPagination<T, R>) => Promise<T[]>);
}
export interface GotRequestFunction {
(url: string | URL, options?: OptionsOfTextResponseBody): CancelableRequest<Response<string>>;
<T>(url: string | URL, options?: OptionsOfJSONResponseBody): CancelableRequest<Response<T>>;
(url: string | URL, options?: OptionsOfBufferResponseBody): CancelableRequest<Response<Buffer>>;
(url: string | URL, options?: OptionsOfUnknownResponseBody): CancelableRequest<Response>;
(options: OptionsOfTextResponseBody): CancelableRequest<Response<string>>;
<T>(options: OptionsOfJSONResponseBody): CancelableRequest<Response<T>>;
(options: OptionsOfBufferResponseBody): CancelableRequest<Response<Buffer>>;
(options: OptionsOfUnknownResponseBody): CancelableRequest<Response>;
(url: string | URL, options?: (Merge<OptionsOfTextResponseBody, ResponseBodyOnly>)): CancelableRequest<string>;
<T>(url: string | URL, options?: (Merge<OptionsOfJSONResponseBody, ResponseBodyOnly>)): CancelableRequest<T>;
(url: string | URL, options?: (Merge<OptionsOfBufferResponseBody, ResponseBodyOnly>)): CancelableRequest<Buffer>;
(options: (Merge<OptionsOfTextResponseBody, ResponseBodyOnly>)): CancelableRequest<string>;
<T>(options: (Merge<OptionsOfJSONResponseBody, ResponseBodyOnly>)): CancelableRequest<T>;
(options: (Merge<OptionsOfBufferResponseBody, ResponseBodyOnly>)): CancelableRequest<Buffer>;
(url: string | URL, options?: Merge<Options, {
isStream: true;
}>): Request;
(options: Merge<Options, {
isStream: true;
}>): Request;
(url: string | URL, options?: Options): CancelableRequest | Request;
(options: Options): CancelableRequest | Request;
}
/**
All available HTTP request methods provided by Got.
*/
export declare type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';
interface GotStreamFunction {
(url: string | URL, options?: Merge<Options, {
isStream?: true;
}>): Request;
(options?: Merge<Options, {
isStream?: true;
}>): Request;
}
/**
An instance of `got.stream()`.
*/
export declare type GotStream = GotStreamFunction & Record<HTTPAlias, GotStreamFunction>;
/**
An instance of `got`.
*/
export interface Got extends Record<HTTPAlias, GotRequestFunction>, GotRequestFunction {
/**
Sets `options.isStream` to `true`.
Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
- request
- response
- redirect
- uploadProgress
- downloadProgress
- error
*/
stream: GotStream;
/**
Returns an async iterator.
See pagination.options for more pagination options.
@example
```
(async () => {
const countLimit = 10;
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
pagination: {countLimit}
});
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
})();
```
*/
paginate: GotPaginate;
/**
The Got defaults used in that instance.
*/
defaults: InstanceDefaults;
/**
An error to be thrown when a cache method fails. For example, if the database goes down or there's a filesystem error.
Contains a `code` property with `ERR_CACHE_ACCESS` or a more specific failure code.
*/
CacheError: typeof CacheError;
/**
An error to be thrown when a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
If there is no specific code supplied, `code` defaults to `ERR_GOT_REQUEST_ERROR`.
*/
RequestError: typeof RequestError;
/**
An error to be thrown when reading from response stream fails. Contains a `code` property with
`ERR_READING_RESPONSE_STREAM` or a more specific failure code.
*/
ReadError: typeof ReadError;
/**
An error to be thrown when server response code is 2xx, and parsing body fails. Includes a
`response` property. Contains a `code` property with `ERR_BODY_PARSE_FAILURE` or a more specific failure code.
*/
ParseError: typeof ParseError;
/**
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.
Includes a `response` property. Contains a `code` property with `ERR_NON_2XX_3XX_RESPONSE` or a more specific failure code.
*/
HTTPError: typeof HTTPError;
/**
An error to be thrown when the server redirects you more than ten times.
Includes a `response` property. Contains a `code` property with `ERR_TOO_MANY_REDIRECTS`.
*/
MaxRedirectsError: typeof MaxRedirectsError;
/**
An error to be thrown when given an unsupported protocol. Contains a `code` property with `ERR_UNSUPPORTED_PROTOCOL`.
*/
UnsupportedProtocolError: typeof UnsupportedProtocolError;
/**
An error to be thrown when the request is aborted due to a timeout.
Includes an `event` and `timings` property. Contains a `code` property with `ETIMEDOUT`.
*/
TimeoutError: typeof TimeoutError;
/**
An error to be thrown when the request body is a stream and an error occurs while reading from that stream.
Contains a `code` property with `ERR_UPLOAD` or a more specific failure code.
*/
UploadError: typeof UploadError;
/**
An error to be thrown when the request is aborted with `.cancel()`. Contains a `code` property with `ERR_CANCELED`.
*/
CancelError: typeof CancelError;
/**
Configure a new `got` instance with default `options`.
The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`.
You can access the resolved options with the `.defaults` property on the instance.
Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`.
It is also possible to merges many instances into a single one:
- options are merged using `got.mergeOptions()` (including hooks),
- handlers are stored in an array (you can access them through `instance.defaults.handlers`).
@example
```js
const client = got.extend({
prefixUrl: 'https://example.com',
headers: {
'x-unicorn': 'rainbow'
}
});
client.get('demo');
// HTTP Request =>
// GET /demo HTTP/1.1
// Host: example.com
// x-unicorn: rainbow
```
*/
extend: (...instancesOrOptions: Array<Got | ExtendOptions>) => Got;
/**
Merges multiple `got` instances into the parent.
*/
mergeInstances: (parent: Got, ...instances: Got[]) => Got;
/**
Extends parent options.
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.
Options are deeply merged to a new object. The value of each key is determined as follows:
- If the new property is not defined, the old value is used.
- If the new property is explicitly set to `undefined`:
- If the parent property is a plain `object`, the parent value is deeply cloned.
- Otherwise, `undefined` is used.
- If the parent value is an instance of `URLSearchParams`:
- If the new value is a `string`, an `object` or an instance of `URLSearchParams`, a new `URLSearchParams` instance is created.
The values are merged using [`urlSearchParams.append(key, value)`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append).
The keys defined in the new value override the keys defined in the parent value.
- Otherwise, the only available value is `undefined`.
- If the new property is a plain `object`:
- If the parent property is a plain `object` too, both values are merged recursively into a new `object`.
- Otherwise, only the new value is deeply cloned.
- If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
- Properties that are not enumerable, such as `context`, `body`, `json`, and `form`, will not be merged.
- Otherwise, the new value is assigned to the key.
**Note:** Only Got options are merged! Custom user options should be defined via [`options.context`](#context).
@example
```
const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
const b = {headers: {cow: 'moo', wolf: ['auuu']}};
{...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
```
*/
mergeOptions: (...sources: Options[]) => NormalizedOptions;
}
export {};

2
node_modules/got/dist/source/types.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

1
node_modules/got/dist/source/utils/deep-freeze.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export default function deepFreeze<T extends Record<string, any>>(object: T): Readonly<T>;

12
node_modules/got/dist/source/utils/deep-freeze.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
function deepFreeze(object) {
for (const value of Object.values(object)) {
if (is_1.default.plainObject(value) || is_1.default.array(value)) {
deepFreeze(value);
}
}
return Object.freeze(object);
}
exports.default = deepFreeze;

View File

@ -0,0 +1,2 @@
declare const _default: (message: string) => void;
export default _default;

View File

@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const alreadyWarned = new Set();
exports.default = (message) => {
if (alreadyWarned.has(message)) {
return;
}
alreadyWarned.add(message);
// @ts-expect-error Missing types.
process.emitWarning(`Got: ${message}`, {
type: 'DeprecationWarning'
});
};

9
node_modules/got/license generated vendored Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

130
node_modules/got/package.json generated vendored Normal file
View File

@ -0,0 +1,130 @@
{
"name": "got",
"version": "11.8.5",
"description": "Human-friendly and powerful HTTP request library for Node.js",
"license": "MIT",
"repository": "sindresorhus/got",
"funding": "https://github.com/sindresorhus/got?sponsor=1",
"main": "dist/source",
"engines": {
"node": ">=10.19.0"
},
"scripts": {
"test": "xo && npm run build && nyc --reporter=html --reporter=text ava",
"release": "np",
"build": "del-cli dist && tsc",
"prepare": "npm run build"
},
"files": [
"dist/source"
],
"keywords": [
"http",
"https",
"http2",
"get",
"got",
"url",
"uri",
"request",
"simple",
"curl",
"wget",
"fetch",
"net",
"network",
"gzip",
"brotli",
"requests",
"human-friendly",
"axios",
"superagent",
"node-fetch",
"ky"
],
"dependencies": {
"@sindresorhus/is": "^4.0.0",
"@szmarczak/http-timer": "^4.0.5",
"@types/cacheable-request": "^6.0.1",
"@types/responselike": "^1.0.0",
"cacheable-lookup": "^5.0.3",
"cacheable-request": "^7.0.2",
"decompress-response": "^6.0.0",
"http2-wrapper": "^1.0.0-beta.5.2",
"lowercase-keys": "^2.0.0",
"p-cancelable": "^2.0.0",
"responselike": "^2.0.0"
},
"devDependencies": {
"@ava/typescript": "^1.1.1",
"@sindresorhus/tsconfig": "^0.7.0",
"@sinonjs/fake-timers": "^6.0.1",
"@types/benchmark": "^1.0.33",
"@types/express": "^4.17.7",
"@types/node": "^14.14.0",
"@types/node-fetch": "^2.5.7",
"@types/pem": "^1.9.5",
"@types/pify": "^3.0.2",
"@types/request": "^2.48.5",
"@types/sinon": "^9.0.5",
"@types/tough-cookie": "^4.0.0",
"ava": "^3.11.1",
"axios": "^0.20.0",
"benchmark": "^2.1.4",
"coveralls": "^3.1.0",
"create-test-server": "^3.0.1",
"del-cli": "^3.0.1",
"delay": "^4.4.0",
"express": "^4.17.1",
"form-data": "^3.0.0",
"get-stream": "^6.0.0",
"nock": "^13.0.4",
"node-fetch": "^2.6.0",
"np": "^6.4.0",
"nyc": "^15.1.0",
"p-event": "^4.2.0",
"pem": "^1.14.4",
"pify": "^5.0.0",
"sinon": "^9.0.3",
"slow-stream": "0.0.4",
"tempy": "^1.0.0",
"to-readable-stream": "^2.1.0",
"tough-cookie": "^4.0.0",
"typescript": "4.0.3",
"xo": "^0.34.1"
},
"types": "dist/source",
"sideEffects": false,
"ava": {
"files": [
"test/*"
],
"timeout": "1m",
"typescript": {
"rewritePaths": {
"test/": "dist/test/"
}
}
},
"nyc": {
"extension": [
".ts"
],
"exclude": [
"**/test/**"
]
},
"xo": {
"ignores": [
"documentation/examples/*"
],
"rules": {
"@typescript-eslint/no-empty-function": "off",
"node/prefer-global/url": "off",
"node/prefer-global/url-search-params": "off",
"import/no-anonymous-default-export": "off",
"@typescript-eslint/no-implicit-any-catch": "off"
}
},
"runkitExampleFilename": "./documentation/examples/runkit-example.js"
}

2477
node_modules/got/readme.md generated vendored Normal file

File diff suppressed because it is too large Load Diff