This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

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

@@ -0,0 +1,3 @@
import Request from '../core/index.js';
import { type CancelableRequest } from './types.js';
export default function asPromise<T>(firstRequest?: Request): CancelableRequest<T>;

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

@@ -0,0 +1,158 @@
import { EventEmitter } from 'node:events';
import is from '@sindresorhus/is';
import PCancelable from 'p-cancelable';
import { HTTPError, RetryError, } from '../core/errors.js';
import Request from '../core/index.js';
import { parseBody, isResponseOk } from '../core/response.js';
import proxyEvents from '../core/utils/proxy-events.js';
import { CancelError } from './types.js';
const proxiedRequestEvents = [
'request',
'response',
'redirect',
'uploadProgress',
'downloadProgress',
];
export default function asPromise(firstRequest) {
let globalRequest;
let globalResponse;
let normalizedOptions;
const emitter = new EventEmitter();
const promise = new PCancelable((resolve, reject, onCancel) => {
onCancel(() => {
globalRequest.destroy();
});
onCancel.shouldReject = false;
onCancel(() => {
reject(new CancelError(globalRequest));
});
const makeRequest = (retryCount) => {
// Errors when a new request is made after the promise settles.
// Used to detect a race condition.
// See https://github.com/sindresorhus/got/issues/1489
onCancel(() => { });
const request = firstRequest ?? new Request(undefined, undefined, normalizedOptions);
request.retryCount = retryCount;
request._noPipe = true;
globalRequest = request;
request.once('response', async (response) => {
// Parse body
const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase();
const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br';
const { options } = request;
if (isCompressed && !options.decompress) {
response.body = response.rawBody;
}
else {
try {
response.body = parseBody(response, options.responseType, options.parseJson, options.encoding);
}
catch (error) {
// Fall back to `utf8`
response.body = response.rawBody.toString();
if (isResponseOk(response)) {
request._beforeError(error);
return;
}
}
}
try {
const hooks = options.hooks.afterResponse;
for (const [index, hook] of hooks.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) => {
options.merge(updatedOptions);
options.prefixUrl = '';
if (updatedOptions.url) {
options.url = updatedOptions.url;
}
// Remove any further hooks for that request, because we'll call them anyway.
// The loop continues. We don't want duplicates (asPromise recursion).
options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
throw new RetryError(request);
});
if (!(is.object(response) && is.number(response.statusCode) && !is.nullOrUndefined(response.body))) {
throw new TypeError('The `afterResponse` hook returned an invalid value');
}
}
}
catch (error) {
request._beforeError(error);
return;
}
globalResponse = response;
if (!isResponseOk(response)) {
request._beforeError(new HTTPError(response));
return;
}
request.destroy();
resolve(request.options.resolveBodyOnly ? response.body : response);
});
const onError = (error) => {
if (promise.isCanceled) {
return;
}
const { options } = request;
if (error instanceof HTTPError && !options.throwHttpErrors) {
const { response } = error;
request.destroy();
resolve(request.options.resolveBodyOnly ? response.body : response);
return;
}
reject(error);
};
request.once('error', onError);
const previousBody = request.options?.body;
request.once('retry', (newRetryCount, error) => {
firstRequest = undefined;
const newBody = request.options.body;
if (previousBody === newBody && is.nodeStream(newBody)) {
error.message = 'Cannot retry with consumed body stream';
onError(error);
return;
}
// This is needed! We need to reuse `request.options` because they can get modified!
// For example, by calling `promise.json()`.
normalizedOptions = request.options;
makeRequest(newRetryCount);
});
proxyEvents(request, emitter, proxiedRequestEvents);
if (is.undefined(firstRequest)) {
void request.flush();
}
};
makeRequest(0);
});
promise.on = (event, fn) => {
emitter.on(event, fn);
return promise;
};
promise.off = (event, fn) => {
emitter.off(event, fn);
return promise;
};
const shortcut = (responseType) => {
const newPromise = (async () => {
// Wait until downloading has ended
await promise;
const { options } = globalResponse.request;
return parseBody(globalResponse, responseType, options.parseJson, options.encoding);
})();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise;
};
promise.json = () => {
if (globalRequest.options) {
const { headers } = globalRequest.options;
if (!globalRequest.writableFinished && !('accept' in headers)) {
headers.accept = 'application/json';
}
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}

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

@@ -0,0 +1,38 @@
/// <reference types="node" resolution-mode="require"/>
import type { Buffer } from 'node:buffer';
import type PCancelable from 'p-cancelable';
import { RequestError } from '../core/errors.js';
import type Request from '../core/index.js';
import type { RequestEvents } from '../core/index.js';
import type { Response } from '../core/response.js';
/**
An error to be thrown when the request is aborted with `.cancel()`.
*/
export declare class CancelError extends RequestError {
readonly response: Response;
constructor(request: Request);
/**
Whether the promise is canceled.
*/
get isCanceled(): boolean;
}
export interface CancelableRequest<T extends Response | Response['body'] = Response['body']> extends PCancelable<T>, RequestEvents<CancelableRequest<T>> {
/**
A shortcut method that gives a Promise returning a JSON object.
It is semantically the same as settings `options.resolveBodyOnly` to `true` and `options.responseType` to `'json'`.
*/
json: <ReturnType>() => CancelableRequest<ReturnType>;
/**
A shortcut method that gives a Promise returning a [Buffer](https://nodejs.org/api/buffer.html).
It is semantically the same as settings `options.resolveBodyOnly` to `true` and `options.responseType` to `'buffer'`.
*/
buffer: () => CancelableRequest<Buffer>;
/**
A shortcut method that gives a Promise returning a string.
It is semantically the same as settings `options.resolveBodyOnly` to `true` and `options.responseType` to `'text'`.
*/
text: () => CancelableRequest<string>;
}

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

@@ -0,0 +1,17 @@
import { RequestError } from '../core/errors.js';
/**
An error to be thrown when the request is aborted with `.cancel()`.
*/
export class CancelError extends RequestError {
constructor(request) {
super('Promise was canceled', {}, request);
this.name = 'CancelError';
this.code = 'ERR_CANCELED';
}
/**
Whether the promise is canceled.
*/
get isCanceled() {
return true;
}
}

View File

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

View File

@@ -0,0 +1,29 @@
const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue, }) => {
if (error.name === 'RetryError') {
return 1;
}
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) {
// In this case `computedValue` is `options.request.timeout`
if (retryAfter > computedValue) {
return 0;
}
return retryAfter;
}
if (error.response.statusCode === 413) {
return 0;
}
}
const noise = Math.random() * retryOptions.noise;
return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise;
};
export default calculateRetryDelay;

90
node_modules/got/dist/source/core/errors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,90 @@
/// <reference types="node" resolution-mode="require"/>
import type { Timings } from '@szmarczak/http-timer';
import type Options from './options.js';
import type { TimeoutError as TimedOutTimeoutError } from './timed-out.js';
import type { PlainResponse, Response } from './response.js';
import type Request from './index.js';
type Error = NodeJS.ErrnoException;
/**
An error to be thrown when a request fails.
Contains a `code` property with error class code, like `ECONNREFUSED`.
*/
export declare class RequestError extends Error {
input?: string;
code: string;
stack: string;
readonly options: Options;
readonly response?: Response;
readonly request?: Request;
readonly timings?: Timings;
constructor(message: string, error: Partial<Error & {
code?: string;
}>, self: Request | Options);
}
/**
An error to be thrown when the server redirects you more than ten times.
Includes a `response` property.
*/
export declare class MaxRedirectsError extends RequestError {
readonly response: Response;
readonly request: Request;
readonly timings: Timings;
constructor(request: Request);
}
/**
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.
*/
export declare class HTTPError extends RequestError {
readonly response: Response;
readonly request: Request;
readonly timings: Timings;
constructor(response: PlainResponse);
}
/**
An error to be thrown when a cache method fails.
For example, if the database goes down or there's a filesystem error.
*/
export declare class CacheError extends RequestError {
readonly request: Request;
constructor(error: Error, request: Request);
}
/**
An error to be thrown when the request body is a stream and an error occurs while reading from that stream.
*/
export declare class UploadError extends RequestError {
readonly request: Request;
constructor(error: Error, request: Request);
}
/**
An error to be thrown when the request is aborted due to a timeout.
Includes an `event` and `timings` property.
*/
export declare class TimeoutError extends RequestError {
readonly request: Request;
readonly timings: Timings;
readonly event: string;
constructor(error: TimedOutTimeoutError, timings: Timings, request: Request);
}
/**
An error to be thrown when reading from response stream fails.
*/
export declare class ReadError extends RequestError {
readonly request: Request;
readonly response: Response;
readonly timings: Timings;
constructor(error: Error, request: Request);
}
/**
An error which always triggers a new retry when thrown.
*/
export declare class RetryError extends RequestError {
constructor(request: Request);
}
/**
An error to be thrown when the request is aborted by AbortController.
*/
export declare class AbortError extends RequestError {
constructor(request: Request);
}
export {};

178
node_modules/got/dist/source/core/errors.js generated vendored Normal file
View File

@@ -0,0 +1,178 @@
import is from '@sindresorhus/is';
// A hacky check to prevent circular references.
function isRequest(x) {
return is.object(x) && '_onResponse' in x;
}
/**
An error to be thrown when a request fails.
Contains a `code` property with error class code, like `ECONNREFUSED`.
*/
export class RequestError extends Error {
constructor(message, error, self) {
super(message);
Object.defineProperty(this, "input", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "code", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "stack", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "response", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "request", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "timings", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Error.captureStackTrace(this, this.constructor);
this.name = 'RequestError';
this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR';
this.input = error.input;
if (isRequest(self)) {
Object.defineProperty(this, 'request', {
enumerable: false,
value: self,
});
Object.defineProperty(this, 'response', {
enumerable: false,
value: self.response,
});
this.options = self.options;
}
else {
this.options = self;
}
this.timings = this.request?.timings;
// Recover the original stacktrace
if (is.string(error.stack) && is.string(this.stack)) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse();
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse();
// Remove duplicated traces
while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) {
thisStackTrace.shift();
}
this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`;
}
}
}
/**
An error to be thrown when the server redirects you more than ten times.
Includes a `response` property.
*/
export class MaxRedirectsError extends RequestError {
constructor(request) {
super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);
this.name = 'MaxRedirectsError';
this.code = 'ERR_TOO_MANY_REDIRECTS';
}
}
/**
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.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export class HTTPError extends RequestError {
constructor(response) {
super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);
this.name = 'HTTPError';
this.code = 'ERR_NON_2XX_3XX_RESPONSE';
}
}
/**
An error to be thrown when a cache method fails.
For example, if the database goes down or there's a filesystem error.
*/
export class CacheError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'CacheError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code;
}
}
/**
An error to be thrown when the request body is a stream and an error occurs while reading from that stream.
*/
export class UploadError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'UploadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code;
}
}
/**
An error to be thrown when the request is aborted due to a timeout.
Includes an `event` and `timings` property.
*/
export class TimeoutError extends RequestError {
constructor(error, timings, request) {
super(error.message, error, request);
Object.defineProperty(this, "timings", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "event", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
}
}
/**
An error to be thrown when reading from response stream fails.
*/
export class ReadError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'ReadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code;
}
}
/**
An error which always triggers a new retry when thrown.
*/
export class RetryError extends RequestError {
constructor(request) {
super('Retrying', {}, request);
this.name = 'RetryError';
this.code = 'ERR_RETRYING';
}
}
/**
An error to be thrown when the request is aborted by AbortController.
*/
export class AbortError extends RequestError {
constructor(request) {
super('This operation was aborted.', {}, request);
this.code = 'ERR_ABORTED';
this.name = 'AbortError';
}
}

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

@@ -0,0 +1,191 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { Duplex } from 'node:stream';
import { URL } from 'node:url';
import type { ClientRequest } from 'node:http';
import type { Socket } from 'node:net';
import type { Timings } from '@szmarczak/http-timer';
import Options from './options.js';
import { type PlainResponse, type Response } from './response.js';
import { RequestError } from './errors.js';
type Error = NodeJS.ErrnoException;
export type Progress = {
percent: number;
transferred: number;
total?: number;
};
export type GotEventFunction<T> =
/**
`request` event to get the request object of the request.
__Tip__: You can use `request` event to abort requests.
@example
```
import got from 'got';
got.stream('https://github.com')
.on('request', request => setTimeout(() => request.destroy(), 50));
```
*/
((name: 'request', listener: (request: ClientRequest) => void) => T)
/**
The `response` event to get the response object of the final request.
*/
& (<R extends Response>(name: 'response', listener: (response: R) => void) => T)
/**
The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
*/
& (<R extends Response, N extends Options>(name: 'redirect', listener: (response: R, nextOptions: N) => void) => T)
/**
Progress events for uploading (sending a request) and downloading (receiving a response).
The `progress` argument is an object like:
```
{
percent: 0.1,
transferred: 1024,
total: 10240
}
```
If the `content-length` header is missing, `total` will be `undefined`.
@example
```
import got from 'got';
const response = await got('https://sindresorhus.com')
.on('downloadProgress', progress => {
// Report download progress
})
.on('uploadProgress', progress => {
// Report upload progress
});
console.log(response);
```
*/
& ((name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void) => T)
/**
To enable retrying on a Got stream, it is required to have a `retry` handler attached.
When this event is emitted, you should reset the stream you were writing to and prepare the body again.
See `got.options.retry` for more information.
*/
& ((name: 'retry', listener: (retryCount: number, error: RequestError) => void) => T);
export type RequestEvents<T> = {
on: GotEventFunction<T>;
once: GotEventFunction<T>;
off: GotEventFunction<T>;
};
type UrlType = ConstructorParameters<typeof Options>[0];
type OptionsType = ConstructorParameters<typeof Options>[1];
type DefaultsType = ConstructorParameters<typeof Options>[2];
export default class Request extends Duplex implements RequestEvents<Request> {
['constructor']: typeof Request;
_noPipe?: boolean;
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
private _requestOptions;
private _stopRetry;
private _downloadedSize;
private _uploadedSize;
private _stopReading;
private readonly _pipedServerResponses;
private _request?;
private _responseSize?;
private _bodySize?;
private _unproxyEvents;
private _isFromCache?;
private _cannotHaveBody;
private _triggerRead;
private _jobs;
private _cancelTimeouts;
private readonly _removeListeners;
private _nativeResponse?;
private _flushed;
private _aborted;
private _requestInitialized;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType);
flush(): Promise<void>;
_beforeError(error: Error): void;
_read(): void;
_write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void;
_final(callback: (error?: Error | null) => void): void;
_destroy(error: Error | null, callback: (error: Error | null) => void): void;
pipe<T extends NodeJS.WritableStream>(destination: T, options?: {
end?: boolean;
}): T;
unpipe<T extends NodeJS.WritableStream>(destination: T): this;
private _finalizeBody;
private _onResponseBase;
private _setRawBody;
private _onResponse;
private _onRequest;
private _asyncWrite;
private _sendBody;
private _prepareCache;
private _createCacheableRequest;
private _makeRequest;
private _error;
private _writeRequest;
/**
The remote IP address.
*/
get ip(): string | undefined;
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean;
get socket(): Socket | undefined;
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress;
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress;
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined;
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined;
get reusedSocket(): boolean | undefined;
}
export {};

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

File diff suppressed because it is too large Load Diff

1256
node_modules/got/dist/source/core/options.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1653
node_modules/got/dist/source/core/options.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
export default function parseLinkHeader(link: string): {
reference: string;
parameters: Record<string, string>;
}[];

33
node_modules/got/dist/source/core/parse-link-header.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
export default function parseLinkHeader(link) {
const parsed = [];
const items = link.split(',');
for (const item of items) {
// https://tools.ietf.org/html/rfc5988#section-5
const [rawUriReference, ...rawLinkParameters] = item.split(';');
const trimmedUriReference = rawUriReference.trim();
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
if (trimmedUriReference[0] !== '<' || trimmedUriReference[trimmedUriReference.length - 1] !== '>') {
throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`);
}
const reference = trimmedUriReference.slice(1, -1);
const parameters = {};
if (rawLinkParameters.length === 0) {
throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`);
}
for (const rawParameter of rawLinkParameters) {
const trimmedRawParameter = rawParameter.trim();
const center = trimmedRawParameter.indexOf('=');
if (center === -1) {
throw new Error(`Failed to parse Link header: ${link}`);
}
const name = trimmedRawParameter.slice(0, center).trim();
const value = trimmedRawParameter.slice(center + 1).trim();
parameters[name] = value;
}
parsed.push({
reference,
parameters,
});
}
return parsed;
}

110
node_modules/got/dist/source/core/response.d.ts generated vendored Normal file
View File

@@ -0,0 +1,110 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import type { Buffer } from 'node:buffer';
import type { URL } from 'node:url';
import type { IncomingMessageWithTimings, Timings } from '@szmarczak/http-timer';
import { RequestError } from './errors.js';
import type { ParseJsonFunction, ResponseType } from './options.js';
import type Request from './index.js';
export type PlainResponse = {
/**
The original request URL.
*/
requestUrl: URL;
/**
The redirect URLs.
*/
redirectUrls: URL[];
/**
- `options` - The Got options that were set on this request.
__Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest).
*/
request: Request;
/**
The remote IP address.
This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86).
__Note__: Not available when the response is cached.
*/
ip?: string;
/**
Whether the response was retrieved from the cache.
*/
isFromCache: boolean;
/**
The status code of the response.
*/
statusCode: number;
/**
The request URL or the final URL after redirects.
*/
url: string;
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
timings: Timings;
/**
The number of times the request was retried.
*/
retryCount: number;
/**
The raw result of the request.
*/
rawBody?: Buffer;
/**
The result of the request.
*/
body?: unknown;
/**
Whether the response was successful.
__Note__: Got throws automatically when `response.ok` is `false` and `throwHttpErrors` is `true`.
*/
ok: boolean;
} & IncomingMessageWithTimings;
export type Response<T = unknown> = {
/**
The result of the request.
*/
body: T;
/**
The raw result of the request.
*/
rawBody: Buffer;
} & PlainResponse;
export declare const isResponseOk: (response: PlainResponse) => boolean;
/**
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);
}
export declare const parseBody: (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: BufferEncoding) => unknown;

39
node_modules/got/dist/source/core/response.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import { RequestError } from './errors.js';
export const isResponseOk = (response) => {
const { statusCode } = response;
const limitStatusCode = response.request.options.followRedirect ? 299 : 399;
return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
};
/**
An error to be thrown when server response code is 2xx, and parsing body fails.
Includes a `response` property.
*/
export class ParseError extends RequestError {
constructor(error, response) {
const { options } = response.request;
super(`${error.message} in "${options.url.toString()}"`, error, response.request);
this.name = 'ParseError';
this.code = 'ERR_BODY_PARSE_FAILURE';
}
}
export 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(encoding));
}
if (responseType === 'buffer') {
return rawBody;
}
}
catch (error) {
throw new ParseError(error, response);
}
throw new ParseError({
message: `Unknown body type '${responseType}'`,
name: 'Error',
}, response);
};

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

@@ -0,0 +1,30 @@
import type { ClientRequest } from 'node:http';
declare const reentry: unique symbol;
type TimedOutOptions = {
host?: string;
hostname?: string;
protocol?: string;
};
export type Delays = {
lookup?: number;
socket?: number;
connect?: number;
secureConnect?: number;
send?: number;
response?: number;
read?: number;
request?: number;
};
export 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);
}
export default function timedOut(request: ClientRequest, delays: Delays, options: TimedOutOptions): () => void;
declare module 'http' {
interface ClientRequest {
[reentry]?: boolean;
}
}
export {};

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

@@ -0,0 +1,138 @@
import net from 'node:net';
import unhandler from './utils/unhandle.js';
const reentry = Symbol('reentry');
const noop = () => { };
export class TimeoutError extends Error {
constructor(threshold, event) {
super(`Timeout awaiting '${event}' for ${threshold}ms`);
Object.defineProperty(this, "event", {
enumerable: true,
configurable: true,
writable: true,
value: event
});
Object.defineProperty(this, "code", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.name = 'TimeoutError';
this.code = 'ETIMEDOUT';
}
}
export default function timedOut(request, delays, options) {
if (reentry in request) {
return noop;
}
request[reentry] = true;
const cancelers = [];
const { once, unhandleAll } = unhandler();
const addTimeout = (delay, callback, event) => {
const timeout = setTimeout(callback, delay, delay, event);
timeout.unref?.();
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;
}
});
if (typeof delays.request !== 'undefined') {
const cancelTimeout = addTimeout(delays.request, timeoutHandler, 'request');
once(request, 'response', (response) => {
once(response, 'end', cancelTimeout);
});
}
if (typeof delays.socket !== 'undefined') {
const { socket } = delays;
const socketTimeoutHandler = () => {
timeoutHandler(socket, 'socket');
};
request.setTimeout(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);
});
}
const hasLookup = typeof delays.lookup !== 'undefined';
const hasConnect = typeof delays.connect !== 'undefined';
const hasSecureConnect = typeof delays.secureConnect !== 'undefined';
const hasSend = typeof delays.send !== 'undefined';
if (hasLookup || hasConnect || hasSecureConnect || hasSend) {
once(request, 'socket', (socket) => {
const { socketPath } = request;
/* istanbul ignore next: hard to test */
if (socket.connecting) {
const hasPath = Boolean(socketPath ?? net.isIP(hostname ?? host ?? '') !== 0);
if (hasLookup && !hasPath && typeof socket.address().address === 'undefined') {
const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
once(socket, 'lookup', cancelTimeout);
}
if (hasConnect) {
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 (hasSecureConnect && options.protocol === 'https:') {
once(socket, 'connect', () => {
const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');
once(socket, 'secureConnect', cancelTimeout);
});
}
}
if (hasSend) {
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);
});
}
if (typeof delays.read !== 'undefined') {
once(request, 'response', (response) => {
const cancelTimeout = addTimeout(delays.read, timeoutHandler, 'read');
once(response, 'end', cancelTimeout);
});
}
return cancelTimeouts;
}

View File

@@ -0,0 +1,3 @@
/// <reference types="node" resolution-mode="require"/>
import type { ClientRequestArgs } from 'node:http';
export default function getBodySize(body: unknown, headers: ClientRequestArgs['headers']): Promise<number | undefined>;

View File

@@ -0,0 +1,22 @@
import { Buffer } from 'node:buffer';
import { promisify } from 'node:util';
import is from '@sindresorhus/is';
import isFormData from './is-form-data.js';
export default async function getBodySize(body, headers) {
if (headers && 'content-length' in headers) {
return Number(headers['content-length']);
}
if (!body) {
return 0;
}
if (is.string(body)) {
return Buffer.byteLength(body);
}
if (is.buffer(body)) {
return body.length;
}
if (isFormData(body)) {
return promisify(body.getLength.bind(body))();
}
return undefined;
}

View File

@@ -0,0 +1,5 @@
/// <reference types="node" resolution-mode="require"/>
import type { Writable, Readable } from 'node:stream';
import type { ClientRequest } from 'node:http';
declare function isClientRequest(clientRequest: Writable | Readable): clientRequest is ClientRequest;
export default isClientRequest;

View File

@@ -0,0 +1,4 @@
function isClientRequest(clientRequest) {
return clientRequest.writable && !clientRequest.writableEnded;
}
export default isClientRequest;

View File

@@ -0,0 +1,8 @@
/// <reference types="node" resolution-mode="require"/>
import type { Readable } from 'node:stream';
type FormData = {
getBoundary: () => string;
getLength: (callback: (error: Error | null, length: number) => void) => void;
} & Readable;
export default function isFormData(body: unknown): body is FormData;
export {};

View File

@@ -0,0 +1,4 @@
import is from '@sindresorhus/is';
export default function isFormData(body) {
return is.nodeStream(body) && is.function_(body.getBoundary);
}

View File

@@ -0,0 +1,3 @@
/// <reference types="node" resolution-mode="require"/>
import type { URL } from 'url';
export default function isUnixSocketURL(url: URL): boolean;

View File

@@ -0,0 +1,4 @@
// eslint-disable-next-line @typescript-eslint/naming-convention
export default function isUnixSocketURL(url) {
return url.protocol === 'unix:' || url.hostname === 'unix';
}

View File

@@ -0,0 +1,14 @@
/// <reference types="node" resolution-mode="require"/>
import { URL } from 'node:url';
export type URLOptions = {
href?: string;
protocol?: string;
host?: string;
hostname?: string;
port?: string | number;
pathname?: string;
search?: string;
searchParams?: unknown;
path?: string;
};
export default function optionsToUrl(origin: string, options: URLOptions): URL;

View File

@@ -0,0 +1,50 @@
/* istanbul ignore file: deprecated */
import { URL } from 'node:url';
const keys = [
'protocol',
'host',
'hostname',
'port',
'pathname',
'search',
];
export default function optionsToUrl(origin, options) {
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}//${options.hostname ?? options.host ?? ''}`;
}
const url = new 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" resolution-mode="require"/>
import type { EventEmitter } from 'node:events';
export default function proxyEvents(from: EventEmitter, to: EventEmitter, events: Readonly<string[]>): () => void;

View File

@@ -0,0 +1,15 @@
export default function proxyEvents(from, to, events) {
const eventFunctions = {};
for (const event of events) {
const eventFunction = (...args) => {
to.emit(event, ...args);
};
eventFunctions[event] = eventFunction;
from.on(event, eventFunction);
}
return () => {
for (const [event, eventFunction] of Object.entries(eventFunctions)) {
from.off(event, eventFunction);
}
};
}

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

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

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

@@ -0,0 +1,20 @@
// 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.
export default function unhandle() {
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 @@
/// <reference types="node" resolution-mode="require"/>
import type { URL, UrlWithStringQuery } from 'node:url';
export type LegacyUrlOptions = {
protocol: string;
hostname: string;
host: string;
hash: string | null;
search: string | null;
pathname: string;
href: string;
path: string;
port?: number;
auth?: string;
};
export default function urlToOptions(url: URL | UrlWithStringQuery): LegacyUrlOptions;

View File

@@ -0,0 +1,22 @@
import is from '@sindresorhus/is';
export default function urlToOptions(url) {
// Cast to URL
url = url;
const options = {
protocol: url.protocol,
hostname: is.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.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,38 @@
export default class WeakableMap {
constructor() {
Object.defineProperty(this, "weakMap", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "map", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
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);
}
}

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

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

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

@@ -0,0 +1,187 @@
import is, { assert } from '@sindresorhus/is';
import asPromise from './as-promise/index.js';
import Request from './core/index.js';
import Options from './core/options.js';
// The `delay` package weighs 10KB (!)
const delay = async (ms) => new Promise(resolve => {
setTimeout(resolve, ms);
});
const isGotInstance = (value) => is.function_(value);
const aliases = [
'get',
'post',
'put',
'patch',
'head',
'delete',
];
const create = (defaults) => {
defaults = {
options: new Options(undefined, undefined, defaults.options),
handlers: [...defaults.handlers],
mutableDefaults: defaults.mutableDefaults,
};
Object.defineProperty(defaults, 'mutableDefaults', {
enumerable: true,
configurable: false,
writable: false,
});
// Got interface
const got = ((url, options, defaultOptions = defaults.options) => {
const request = new Request(url, options, defaultOptions);
let promise;
const lastHandler = (normalized) => {
// Note: `options` is `undefined` when `new Options(...)` fails
request.options = normalized;
request._noPipe = !normalized.isStream;
void request.flush();
if (normalized.isStream) {
return request;
}
if (!promise) {
promise = asPromise(request);
}
return promise;
};
let iteration = 0;
const iterateHandlers = (newOptions) => {
const handler = defaults.handlers[iteration++] ?? lastHandler;
const result = handler(newOptions, iterateHandlers);
if (is.promise(result) && !request.options.isStream) {
if (!promise) {
promise = asPromise(request);
}
if (result !== promise) {
const descriptors = Object.getOwnPropertyDescriptors(promise);
for (const key in descriptors) {
if (key in result) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete descriptors[key];
}
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(result, descriptors);
result.cancel = promise.cancel;
}
}
return result;
};
return iterateHandlers(request.options);
});
got.extend = (...instancesOrOptions) => {
const options = new Options(undefined, undefined, defaults.options);
const handlers = [...defaults.handlers];
let mutableDefaults;
for (const value of instancesOrOptions) {
if (isGotInstance(value)) {
options.merge(value.defaults.options);
handlers.push(...value.defaults.handlers);
mutableDefaults = value.defaults.mutableDefaults;
}
else {
options.merge(value);
if (value.handlers) {
handlers.push(...value.handlers);
}
mutableDefaults = value.mutableDefaults;
}
}
return create({
options,
handlers,
mutableDefaults: Boolean(mutableDefaults),
});
};
// Pagination
const paginateEach = (async function* (url, options) {
let normalizedOptions = new Options(url, options, defaults.options);
normalizedOptions.resolveBodyOnly = false;
const { pagination } = normalizedOptions;
assert.function_(pagination.transform);
assert.function_(pagination.shouldContinue);
assert.function_(pagination.filter);
assert.function_(pagination.paginate);
assert.number(pagination.countLimit);
assert.number(pagination.requestLimit);
assert.number(pagination.backoff);
const allItems = [];
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);
}
// eslint-disable-next-line no-await-in-loop
const response = (await got(undefined, undefined, normalizedOptions));
// eslint-disable-next-line no-await-in-loop
const parsed = await pagination.transform(response);
const currentItems = [];
assert.array(parsed);
for (const item of parsed) {
if (pagination.filter({ item, currentItems, allItems })) {
if (!pagination.shouldContinue({ item, currentItems, allItems })) {
return;
}
yield item;
if (pagination.stackAllItems) {
allItems.push(item);
}
currentItems.push(item);
if (--countLimit <= 0) {
return;
}
}
}
const optionsToMerge = pagination.paginate({
response,
currentItems,
allItems,
});
if (optionsToMerge === false) {
return;
}
if (optionsToMerge === response.request.options) {
normalizedOptions = response.request.options;
}
else {
normalizedOptions.merge(optionsToMerge);
assert.any([is.urlInstance, is.undefined], optionsToMerge.url);
if (optionsToMerge.url !== undefined) {
normalizedOptions.prefixUrl = '';
normalizedOptions.url = optionsToMerge.url;
}
}
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) => got(url, { ...options, method, isStream: true }));
}
if (!defaults.mutableDefaults) {
Object.freeze(defaults.handlers);
defaults.options.freeze();
}
Object.defineProperty(got, 'defaults', {
value: defaults,
writable: false,
configurable: false,
enumerable: true,
});
return got;
};
export default create;

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

@@ -0,0 +1,15 @@
declare const got: import("./types.js").Got;
export default got;
export { got };
export { default as Options } from './core/options.js';
export * from './core/options.js';
export * from './core/response.js';
export type { default as Request } from './core/index.js';
export * from './core/index.js';
export * from './core/errors.js';
export type { Delays } from './core/timed-out.js';
export { default as calculateRetryDelay } from './core/calculate-retry-delay.js';
export * from './as-promise/types.js';
export * from './types.js';
export { default as create } from './create.js';
export { default as parseLinkHeader } from './core/parse-link-header.js';

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

@@ -0,0 +1,20 @@
import create from './create.js';
import Options from './core/options.js';
const defaults = {
options: new Options(),
handlers: [],
mutableDefaults: false,
};
const got = create(defaults);
export default got;
export { got };
export { default as Options } from './core/options.js';
export * from './core/options.js';
export * from './core/response.js';
export * from './core/index.js';
export * from './core/errors.js';
export { default as calculateRetryDelay } from './core/calculate-retry-delay.js';
export * from './as-promise/types.js';
export * from './types.js';
export { default as create } from './create.js';
export { default as parseLinkHeader } from './core/parse-link-header.js';

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

@@ -0,0 +1,263 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import type { Buffer } from 'node:buffer';
import type { URL } from 'node:url';
import type { CancelableRequest } from './as-promise/types.js';
import type { Response } from './core/response.js';
import type Options from './core/options.js';
import type { PaginationOptions, OptionsInit } from './core/options.js';
import type Request from './core/index.js';
type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
/**
Defaults for each Got instance.
*/
export type InstanceDefaults = {
/**
An object containing the default options of Got.
*/
options: 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;
};
/**
A Request object returned by calling Got, or any of the Got HTTP alias request functions.
*/
export 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 type HandlerFunction = <T extends GotReturn>(options: Options, next: (options: Options) => T) => T | Promise<T>;
/**
The options available for `got.extend()`.
*/
export type ExtendOptions = {
/**
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;
} & OptionsInit;
export type OptionsOfTextResponseBody = Merge<OptionsInit, {
isStream?: false;
resolveBodyOnly?: false;
responseType?: 'text';
}>;
export type OptionsOfJSONResponseBody = Merge<OptionsInit, {
isStream?: false;
resolveBodyOnly?: false;
responseType?: 'json';
}>;
export type OptionsOfBufferResponseBody = Merge<OptionsInit, {
isStream?: false;
resolveBodyOnly?: false;
responseType: 'buffer';
}>;
export type OptionsOfUnknownResponseBody = Merge<OptionsInit, {
isStream?: false;
resolveBodyOnly?: false;
}>;
export type StrictOptions = Except<OptionsInit, 'isStream' | 'responseType' | 'resolveBodyOnly'>;
export type StreamOptions = Merge<OptionsInit, {
isStream?: true;
}>;
type ResponseBodyOnly = {
resolveBodyOnly: true;
};
export type OptionsWithPagination<T = unknown, R = unknown> = Merge<OptionsInit, {
pagination?: PaginationOptions<T, R>;
}>;
/**
An instance of `got.paginate`.
*/
export type 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
```
import got from 'got';
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
```
import got from 'got';
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 type 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<OptionsInit, {
isStream: true;
}>): Request;
(options: Merge<OptionsInit, {
isStream: true;
}>): Request;
(url: string | URL, options?: OptionsInit): CancelableRequest | Request;
(options: OptionsInit): CancelableRequest | Request;
(url: undefined, options: undefined, defaults: Options): CancelableRequest | Request;
};
/**
All available HTTP request methods provided by Got.
*/
export type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';
type GotStreamFunction = ((url?: string | URL, options?: Merge<OptionsInit, {
isStream?: true;
}>) => Request) & ((options?: Merge<OptionsInit, {
isStream?: true;
}>) => Request);
/**
An instance of `got.stream()`.
*/
export type GotStream = GotStreamFunction & Record<HTTPAlias, GotStreamFunction>;
/**
An instance of `got`.
*/
export type Got = {
/**
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
```
import got from 'got';
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;
/**
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
```
import got from 'got';
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;
} & Record<HTTPAlias, GotRequestFunction> & GotRequestFunction;
export {};

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

@@ -0,0 +1 @@
export {};

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.

View File

@@ -0,0 +1,246 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import type { Buffer } from 'node:buffer';
import type { Class, Falsy, TypedArray, ObservableLike, Primitive, WeakRef } from './types.js';
declare const objectTypeNames: readonly ["Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Blob", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "WeakRef", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "FormData", "URLSearchParams", "HTMLElement", "NaN", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array"];
type ObjectTypeName = typeof objectTypeNames[number];
declare const primitiveTypeNames: readonly ["null", "undefined", "string", "number", "bigint", "boolean", "symbol"];
type PrimitiveTypeName = typeof primitiveTypeNames[number];
export type TypeName = ObjectTypeName | PrimitiveTypeName;
declare function is(value: unknown): TypeName;
declare namespace is {
var undefined: (value: unknown) => value is undefined;
var string: (value: unknown) => value is string;
var number: (value: unknown) => value is number;
var positiveNumber: (value: unknown) => value is number;
var negativeNumber: (value: unknown) => value is number;
var bigint: (value: unknown) => value is bigint;
var function_: (value: unknown) => value is Function;
var null_: (value: unknown) => value is null;
var class_: (value: unknown) => value is Class;
var boolean: (value: unknown) => value is boolean;
var symbol: (value: unknown) => value is symbol;
var numericString: (value: unknown) => value is `${number}`;
var array: <T = unknown>(value: unknown, assertion?: ((value: T) => value is T) | undefined) => value is T[];
var buffer: (value: unknown) => value is Buffer;
var blob: (value: unknown) => value is Blob;
var nullOrUndefined: (value: unknown) => value is null | undefined;
var object: (value: unknown) => value is object;
var iterable: <T = unknown>(value: unknown) => value is Iterable<T>;
var asyncIterable: <T = unknown>(value: unknown) => value is AsyncIterable<T>;
var generator: (value: unknown) => value is Generator<unknown, any, unknown>;
var asyncGenerator: (value: unknown) => value is AsyncGenerator<unknown, any, unknown>;
var nativePromise: <T = unknown>(value: unknown) => value is Promise<T>;
var promise: <T = unknown>(value: unknown) => value is Promise<T>;
var generatorFunction: (value: unknown) => value is GeneratorFunction;
var asyncGeneratorFunction: (value: unknown) => value is (...args: any[]) => Promise<unknown>;
var asyncFunction: <T = unknown>(value: unknown) => value is (...args: any[]) => Promise<T>;
var boundFunction: (value: unknown) => value is Function;
var regExp: (value: unknown) => value is RegExp;
var date: (value: unknown) => value is Date;
var error: (value: unknown) => value is Error;
var map: <Key = unknown, Value = unknown>(value: unknown) => value is Map<Key, Value>;
var set: <T = unknown>(value: unknown) => value is Set<T>;
var weakMap: <Key extends object = object, Value = unknown>(value: unknown) => value is WeakMap<Key, Value>;
var weakSet: (value: unknown) => value is WeakSet<object>;
var weakRef: (value: unknown) => value is WeakRef<object>;
var int8Array: (value: unknown) => value is Int8Array;
var uint8Array: (value: unknown) => value is Uint8Array;
var uint8ClampedArray: (value: unknown) => value is Uint8ClampedArray;
var int16Array: (value: unknown) => value is Int16Array;
var uint16Array: (value: unknown) => value is Uint16Array;
var int32Array: (value: unknown) => value is Int32Array;
var uint32Array: (value: unknown) => value is Uint32Array;
var float32Array: (value: unknown) => value is Float32Array;
var float64Array: (value: unknown) => value is Float64Array;
var bigInt64Array: (value: unknown) => value is BigInt64Array;
var bigUint64Array: (value: unknown) => value is BigUint64Array;
var arrayBuffer: (value: unknown) => value is ArrayBuffer;
var sharedArrayBuffer: (value: unknown) => value is SharedArrayBuffer;
var dataView: (value: unknown) => value is DataView;
var enumCase: <T = unknown>(value: unknown, targetEnum: T) => boolean;
var directInstanceOf: <T>(instance: unknown, class_: Class<T>) => instance is T;
var urlInstance: (value: unknown) => value is URL;
var urlString: (value: unknown) => value is string;
var truthy: <T>(value: Falsy | T) => value is T;
var falsy: (value: unknown) => value is Falsy;
var nan: (value: unknown) => boolean;
var primitive: (value: unknown) => value is Primitive;
var integer: (value: unknown) => value is number;
var safeInteger: (value: unknown) => value is number;
var plainObject: <Value = unknown>(value: unknown) => value is Record<PropertyKey, Value>;
var typedArray: (value: unknown) => value is TypedArray;
var arrayLike: <T = unknown>(value: unknown) => value is ArrayLike<T>;
var tupleLike: <T extends TypeGuard<unknown>[]>(value: unknown, guards: [...T]) => value is ResolveTypesOfTypeGuardsTuple<T, []>;
var inRange: (value: number, range: number | number[]) => value is number;
var domElement: (value: unknown) => value is HTMLElement;
var observable: (value: unknown) => value is ObservableLike;
var nodeStream: (value: unknown) => value is NodeStream;
var infinite: (value: unknown) => value is number;
var evenInteger: (value: number) => value is number;
var oddInteger: (value: number) => value is number;
var emptyArray: (value: unknown) => value is never[];
var nonEmptyArray: <T = unknown, Item = unknown>(value: T | Item[]) => value is [Item, ...Item[]];
var emptyString: (value: unknown) => value is "";
var emptyStringOrWhitespace: (value: unknown) => value is string;
var nonEmptyString: (value: unknown) => value is string;
var nonEmptyStringAndNotWhitespace: (value: unknown) => value is string;
var emptyObject: <Key extends string | number | symbol = string>(value: unknown) => value is Record<Key, never>;
var nonEmptyObject: <Key extends string | number | symbol = string, Value = unknown>(value: unknown) => value is Record<Key, Value>;
var emptySet: (value: unknown) => value is Set<never>;
var nonEmptySet: <T = unknown>(value: unknown) => value is Set<T>;
var emptyMap: (value: unknown) => value is Map<never, never>;
var nonEmptyMap: <Key = unknown, Value = unknown>(value: unknown) => value is Map<Key, Value>;
var propertyKey: (value: unknown) => value is PropertyKey;
var formData: (value: unknown) => value is FormData;
var urlSearchParams: (value: unknown) => value is URLSearchParams;
var any: (predicate: Predicate | Predicate[], ...values: unknown[]) => boolean;
var all: (predicate: Predicate, ...values: unknown[]) => boolean;
}
export type ArrayLike<T> = {
readonly [index: number]: T;
readonly length: number;
};
type TypeGuard<T> = (value: unknown) => value is T;
type ResolveTypesOfTypeGuardsTuple<TypeGuardsOfT, ResultOfT extends unknown[] = []> = TypeGuardsOfT extends [TypeGuard<infer U>, ...infer TOthers] ? ResolveTypesOfTypeGuardsTuple<TOthers, [...ResultOfT, U]> : TypeGuardsOfT extends undefined[] ? ResultOfT : never;
export type NodeStream = {
pipe<T extends NodeJS.WritableStream>(destination: T, options?: {
end?: boolean;
}): T;
} & NodeJS.EventEmitter;
export type Predicate = (value: unknown) => boolean;
export declare const enum AssertionTypeDescription {
class_ = "Class",
numericString = "string with a number",
nullOrUndefined = "null or undefined",
iterable = "Iterable",
asyncIterable = "AsyncIterable",
nativePromise = "native Promise",
urlString = "string with a URL",
truthy = "truthy",
falsy = "falsy",
nan = "NaN",
primitive = "primitive",
integer = "integer",
safeInteger = "integer",
plainObject = "plain object",
arrayLike = "array-like",
tupleLike = "tuple-like",
typedArray = "TypedArray",
domElement = "HTMLElement",
nodeStream = "Node.js Stream",
infinite = "infinite number",
emptyArray = "empty array",
nonEmptyArray = "non-empty array",
emptyString = "empty string",
emptyStringOrWhitespace = "empty string or whitespace",
nonEmptyString = "non-empty string",
nonEmptyStringAndNotWhitespace = "non-empty string and not whitespace",
emptyObject = "empty object",
nonEmptyObject = "non-empty object",
emptySet = "empty set",
nonEmptySet = "non-empty set",
emptyMap = "empty map",
nonEmptyMap = "non-empty map",
evenInteger = "even integer",
oddInteger = "odd integer",
positiveNumber = "positive number",
negativeNumber = "negative number",
directInstanceOf = "T",
inRange = "in range",
any = "predicate returns truthy for any value",
all = "predicate returns truthy for all values"
}
type Assert = {
undefined: (value: unknown) => asserts value is undefined;
string: (value: unknown) => asserts value is string;
number: (value: unknown) => asserts value is number;
positiveNumber: (value: unknown) => asserts value is number;
negativeNumber: (value: unknown) => asserts value is number;
bigint: (value: unknown) => asserts value is bigint;
function_: (value: unknown) => asserts value is Function;
null_: (value: unknown) => asserts value is null;
class_: (value: unknown) => asserts value is Class;
boolean: (value: unknown) => asserts value is boolean;
symbol: (value: unknown) => asserts value is symbol;
numericString: (value: unknown) => asserts value is `${number}`;
array: <T = unknown>(value: unknown, assertion?: (element: unknown) => asserts element is T) => asserts value is T[];
buffer: (value: unknown) => asserts value is Buffer;
blob: (value: unknown) => asserts value is Blob;
nullOrUndefined: (value: unknown) => asserts value is null | undefined;
object: <Key extends keyof any = string, Value = unknown>(value: unknown) => asserts value is Record<Key, Value>;
iterable: <T = unknown>(value: unknown) => asserts value is Iterable<T>;
asyncIterable: <T = unknown>(value: unknown) => asserts value is AsyncIterable<T>;
generator: (value: unknown) => asserts value is Generator;
asyncGenerator: (value: unknown) => asserts value is AsyncGenerator;
nativePromise: <T = unknown>(value: unknown) => asserts value is Promise<T>;
promise: <T = unknown>(value: unknown) => asserts value is Promise<T>;
generatorFunction: (value: unknown) => asserts value is GeneratorFunction;
asyncGeneratorFunction: (value: unknown) => asserts value is AsyncGeneratorFunction;
asyncFunction: (value: unknown) => asserts value is Function;
boundFunction: (value: unknown) => asserts value is Function;
regExp: (value: unknown) => asserts value is RegExp;
date: (value: unknown) => asserts value is Date;
error: (value: unknown) => asserts value is Error;
map: <Key = unknown, Value = unknown>(value: unknown) => asserts value is Map<Key, Value>;
set: <T = unknown>(value: unknown) => asserts value is Set<T>;
weakMap: <Key extends object = object, Value = unknown>(value: unknown) => asserts value is WeakMap<Key, Value>;
weakSet: <T extends object = object>(value: unknown) => asserts value is WeakSet<T>;
weakRef: <T extends object = object>(value: unknown) => asserts value is WeakRef<T>;
int8Array: (value: unknown) => asserts value is Int8Array;
uint8Array: (value: unknown) => asserts value is Uint8Array;
uint8ClampedArray: (value: unknown) => asserts value is Uint8ClampedArray;
int16Array: (value: unknown) => asserts value is Int16Array;
uint16Array: (value: unknown) => asserts value is Uint16Array;
int32Array: (value: unknown) => asserts value is Int32Array;
uint32Array: (value: unknown) => asserts value is Uint32Array;
float32Array: (value: unknown) => asserts value is Float32Array;
float64Array: (value: unknown) => asserts value is Float64Array;
bigInt64Array: (value: unknown) => asserts value is BigInt64Array;
bigUint64Array: (value: unknown) => asserts value is BigUint64Array;
arrayBuffer: (value: unknown) => asserts value is ArrayBuffer;
sharedArrayBuffer: (value: unknown) => asserts value is SharedArrayBuffer;
dataView: (value: unknown) => asserts value is DataView;
enumCase: <T = unknown>(value: unknown, targetEnum: T) => asserts value is T[keyof T];
urlInstance: (value: unknown) => asserts value is URL;
urlString: (value: unknown) => asserts value is string;
truthy: <T>(value: T | Falsy) => asserts value is T;
falsy: (value: unknown) => asserts value is Falsy;
nan: (value: unknown) => asserts value is number;
primitive: (value: unknown) => asserts value is Primitive;
integer: (value: unknown) => asserts value is number;
safeInteger: (value: unknown) => asserts value is number;
plainObject: <Value = unknown>(value: unknown) => asserts value is Record<PropertyKey, Value>;
typedArray: (value: unknown) => asserts value is TypedArray;
arrayLike: <T = unknown>(value: unknown) => asserts value is ArrayLike<T>;
tupleLike: <T extends Array<TypeGuard<unknown>>>(value: unknown, guards: [...T]) => asserts value is ResolveTypesOfTypeGuardsTuple<T>;
domElement: (value: unknown) => asserts value is HTMLElement;
observable: (value: unknown) => asserts value is ObservableLike;
nodeStream: (value: unknown) => asserts value is NodeStream;
infinite: (value: unknown) => asserts value is number;
emptyArray: (value: unknown) => asserts value is never[];
nonEmptyArray: <T = unknown, Item = unknown>(value: T | Item[]) => asserts value is [Item, ...Item[]];
emptyString: (value: unknown) => asserts value is '';
emptyStringOrWhitespace: (value: unknown) => asserts value is string;
nonEmptyString: (value: unknown) => asserts value is string;
nonEmptyStringAndNotWhitespace: (value: unknown) => asserts value is string;
emptyObject: <Key extends keyof any = string>(value: unknown) => asserts value is Record<Key, never>;
nonEmptyObject: <Key extends keyof any = string, Value = unknown>(value: unknown) => asserts value is Record<Key, Value>;
emptySet: (value: unknown) => asserts value is Set<never>;
nonEmptySet: <T = unknown>(value: unknown) => asserts value is Set<T>;
emptyMap: (value: unknown) => asserts value is Map<never, never>;
nonEmptyMap: <Key = unknown, Value = unknown>(value: unknown) => asserts value is Map<Key, Value>;
propertyKey: (value: unknown) => asserts value is PropertyKey;
formData: (value: unknown) => asserts value is FormData;
urlSearchParams: (value: unknown) => asserts value is URLSearchParams;
evenInteger: (value: number) => asserts value is number;
oddInteger: (value: number) => asserts value is number;
directInstanceOf: <T>(instance: unknown, class_: Class<T>) => asserts instance is T;
inRange: (value: number, range: number | number[]) => asserts value is number;
any: (predicate: Predicate | Predicate[], ...values: unknown[]) => void | never;
all: (predicate: Predicate, ...values: unknown[]) => void | never;
};
export declare const assert: Assert;
export default is;
export type { Class, TypedArray, ObservableLike, Primitive } from './types.js';

View File

@@ -0,0 +1,454 @@
const typedArrayTypeNames = [
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array',
'BigInt64Array',
'BigUint64Array',
];
function isTypedArrayName(name) {
return typedArrayTypeNames.includes(name);
}
const objectTypeNames = [
'Function',
'Generator',
'AsyncGenerator',
'GeneratorFunction',
'AsyncGeneratorFunction',
'AsyncFunction',
'Observable',
'Array',
'Buffer',
'Blob',
'Object',
'RegExp',
'Date',
'Error',
'Map',
'Set',
'WeakMap',
'WeakSet',
'WeakRef',
'ArrayBuffer',
'SharedArrayBuffer',
'DataView',
'Promise',
'URL',
'FormData',
'URLSearchParams',
'HTMLElement',
'NaN',
...typedArrayTypeNames,
];
function isObjectTypeName(name) {
return objectTypeNames.includes(name);
}
const primitiveTypeNames = [
'null',
'undefined',
'string',
'number',
'bigint',
'boolean',
'symbol',
];
function isPrimitiveTypeName(name) {
return primitiveTypeNames.includes(name);
}
// eslint-disable-next-line @typescript-eslint/ban-types
function isOfType(type) {
return (value) => typeof value === type;
}
const { toString } = Object.prototype;
const getObjectType = (value) => {
const objectTypeName = toString.call(value).slice(8, -1);
if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) {
return 'HTMLElement';
}
if (isObjectTypeName(objectTypeName)) {
return objectTypeName;
}
return undefined;
};
const isObjectOfType = (type) => (value) => getObjectType(value) === type;
function is(value) {
if (value === null) {
return 'null';
}
switch (typeof value) {
case 'undefined': {
return 'undefined';
}
case 'string': {
return 'string';
}
case 'number': {
return Number.isNaN(value) ? 'NaN' : 'number';
}
case 'boolean': {
return 'boolean';
}
case 'function': {
return 'Function';
}
case 'bigint': {
return 'bigint';
}
case 'symbol': {
return 'symbol';
}
default:
}
if (is.observable(value)) {
return 'Observable';
}
if (is.array(value)) {
return 'Array';
}
if (is.buffer(value)) {
return 'Buffer';
}
const tagType = getObjectType(value);
if (tagType) {
return tagType;
}
if (value instanceof String || value instanceof Boolean || value instanceof Number) {
throw new TypeError('Please don\'t use object wrappers for primitive types');
}
return 'Object';
}
is.undefined = isOfType('undefined');
is.string = isOfType('string');
const isNumberType = isOfType('number');
is.number = (value) => isNumberType(value) && !is.nan(value);
is.positiveNumber = (value) => is.number(value) && value > 0;
is.negativeNumber = (value) => is.number(value) && value < 0;
is.bigint = isOfType('bigint');
// eslint-disable-next-line @typescript-eslint/ban-types
is.function_ = isOfType('function');
// eslint-disable-next-line @typescript-eslint/ban-types
is.null_ = (value) => value === null;
is.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');
is.boolean = (value) => value === true || value === false;
is.symbol = isOfType('symbol');
is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value));
is.array = (value, assertion) => {
if (!Array.isArray(value)) {
return false;
}
if (!is.function_(assertion)) {
return true;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return value.every(element => assertion(element));
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call
is.buffer = (value) => value?.constructor?.isBuffer?.(value) ?? false;
is.blob = (value) => isObjectOfType('Blob')(value);
is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); // eslint-disable-line @typescript-eslint/ban-types
is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); // eslint-disable-line @typescript-eslint/ban-types
is.iterable = (value) => is.function_(value?.[Symbol.iterator]);
is.asyncIterable = (value) => is.function_(value?.[Symbol.asyncIterator]);
is.generator = (value) => is.iterable(value) && is.function_(value?.next) && is.function_(value?.throw);
is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw);
is.nativePromise = (value) => isObjectOfType('Promise')(value);
const hasPromiseApi = (value) => is.function_(value?.then)
&& is.function_(value?.catch);
is.promise = (value) => is.nativePromise(value) || hasPromiseApi(value);
is.generatorFunction = isObjectOfType('GeneratorFunction');
is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction';
is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction';
// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types
is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');
is.regExp = isObjectOfType('RegExp');
is.date = isObjectOfType('Date');
is.error = isObjectOfType('Error');
is.map = (value) => isObjectOfType('Map')(value);
is.set = (value) => isObjectOfType('Set')(value);
is.weakMap = (value) => isObjectOfType('WeakMap')(value); // eslint-disable-line @typescript-eslint/ban-types
is.weakSet = (value) => isObjectOfType('WeakSet')(value); // eslint-disable-line @typescript-eslint/ban-types
is.weakRef = (value) => isObjectOfType('WeakRef')(value); // eslint-disable-line @typescript-eslint/ban-types
is.int8Array = isObjectOfType('Int8Array');
is.uint8Array = isObjectOfType('Uint8Array');
is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray');
is.int16Array = isObjectOfType('Int16Array');
is.uint16Array = isObjectOfType('Uint16Array');
is.int32Array = isObjectOfType('Int32Array');
is.uint32Array = isObjectOfType('Uint32Array');
is.float32Array = isObjectOfType('Float32Array');
is.float64Array = isObjectOfType('Float64Array');
is.bigInt64Array = isObjectOfType('BigInt64Array');
is.bigUint64Array = isObjectOfType('BigUint64Array');
is.arrayBuffer = isObjectOfType('ArrayBuffer');
is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer');
is.dataView = isObjectOfType('DataView');
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value);
is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype;
is.urlInstance = (value) => isObjectOfType('URL')(value);
is.urlString = (value) => {
if (!is.string(value)) {
return false;
}
try {
new URL(value); // eslint-disable-line no-new
return true;
}
catch {
return false;
}
};
// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);`
is.truthy = (value) => Boolean(value); // eslint-disable-line unicorn/prefer-native-coercion-functions
// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);`
is.falsy = (value) => !value;
is.nan = (value) => Number.isNaN(value);
is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value);
is.integer = (value) => Number.isInteger(value);
is.safeInteger = (value) => Number.isSafeInteger(value);
is.plainObject = (value) => {
// From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
if (typeof value !== 'object' || value === null) {
return false;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const prototype = Object.getPrototypeOf(value);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
};
is.typedArray = (value) => isTypedArrayName(getObjectType(value));
const isValidLength = (value) => is.safeInteger(value) && value >= 0;
is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
is.tupleLike = (value, guards) => {
if (is.array(guards) && is.array(value) && guards.length === value.length) {
return guards.every((guard, index) => guard(value[index]));
}
return false;
};
is.inRange = (value, range) => {
if (is.number(range)) {
return value >= Math.min(0, range) && value <= Math.max(range, 0);
}
if (is.array(range) && range.length === 2) {
return value >= Math.min(...range) && value <= Math.max(...range);
}
throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);
};
// eslint-disable-next-line @typescript-eslint/naming-convention
const NODE_TYPE_ELEMENT = 1;
// eslint-disable-next-line @typescript-eslint/naming-convention
const DOM_PROPERTIES_TO_CHECK = [
'innerHTML',
'ownerDocument',
'style',
'attributes',
'nodeValue',
];
is.domElement = (value) => is.object(value)
&& value.nodeType === NODE_TYPE_ELEMENT
&& is.string(value.nodeName)
&& !is.plainObject(value)
&& DOM_PROPERTIES_TO_CHECK.every(property => property in value);
is.observable = (value) => {
if (!value) {
return false;
}
// eslint-disable-next-line no-use-extend-native/no-use-extend-native, @typescript-eslint/no-unsafe-call
if (value === value[Symbol.observable]?.()) {
return true;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (value === value['@@observable']?.()) {
return true;
}
return false;
};
is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value);
is.infinite = (value) => value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY;
const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder;
is.evenInteger = isAbsoluteMod2(0);
is.oddInteger = isAbsoluteMod2(1);
is.emptyArray = (value) => is.array(value) && value.length === 0;
is.nonEmptyArray = (value) => is.array(value) && value.length > 0;
is.emptyString = (value) => is.string(value) && value.length === 0;
const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value);
is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);
// TODO: Use `not ''` when the `not` operator is available.
is.nonEmptyString = (value) => is.string(value) && value.length > 0;
// TODO: Use `not ''` when the `not` operator is available.
is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value);
// eslint-disable-next-line unicorn/no-array-callback-reference
is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;
// TODO: Use `not` operator here to remove `Map` and `Set` from type guard:
// - https://github.com/Microsoft/TypeScript/pull/29317
// eslint-disable-next-line unicorn/no-array-callback-reference
is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;
is.emptySet = (value) => is.set(value) && value.size === 0;
is.nonEmptySet = (value) => is.set(value) && value.size > 0;
// eslint-disable-next-line unicorn/no-array-callback-reference
is.emptyMap = (value) => is.map(value) && value.size === 0;
// eslint-disable-next-line unicorn/no-array-callback-reference
is.nonEmptyMap = (value) => is.map(value) && value.size > 0;
// `PropertyKey` is any value that can be used as an object key (string, number, or symbol)
is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value);
is.formData = (value) => isObjectOfType('FormData')(value);
is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value);
const predicateOnArray = (method, predicate, values) => {
if (!is.function_(predicate)) {
throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
}
if (values.length === 0) {
throw new TypeError('Invalid number of values');
}
return method.call(values, predicate);
};
is.any = (predicate, ...values) => {
const predicates = is.array(predicate) ? predicate : [predicate];
return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values));
};
is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);
const assertType = (condition, description, value, options = {}) => {
if (!condition) {
const { multipleValues } = options;
const valuesMessage = multipleValues
? `received values of types ${[
...new Set(value.map(singleValue => `\`${is(singleValue)}\``)),
].join(', ')}`
: `received value of type \`${is(value)}\``;
throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`);
}
};
/* eslint-disable @typescript-eslint/no-confusing-void-expression */
export const assert = {
// Unknowns.
undefined: (value) => assertType(is.undefined(value), 'undefined', value),
string: (value) => assertType(is.string(value), 'string', value),
number: (value) => assertType(is.number(value), 'number', value),
positiveNumber: (value) => assertType(is.positiveNumber(value), "positive number" /* AssertionTypeDescription.positiveNumber */, value),
negativeNumber: (value) => assertType(is.negativeNumber(value), "negative number" /* AssertionTypeDescription.negativeNumber */, value),
bigint: (value) => assertType(is.bigint(value), 'bigint', value),
// eslint-disable-next-line @typescript-eslint/ban-types
function_: (value) => assertType(is.function_(value), 'Function', value),
null_: (value) => assertType(is.null_(value), 'null', value),
class_: (value) => assertType(is.class_(value), "Class" /* AssertionTypeDescription.class_ */, value),
boolean: (value) => assertType(is.boolean(value), 'boolean', value),
symbol: (value) => assertType(is.symbol(value), 'symbol', value),
numericString: (value) => assertType(is.numericString(value), "string with a number" /* AssertionTypeDescription.numericString */, value),
array: (value, assertion) => {
const assert = assertType;
assert(is.array(value), 'Array', value);
if (assertion) {
// eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference
value.forEach(assertion);
}
},
buffer: (value) => assertType(is.buffer(value), 'Buffer', value),
blob: (value) => assertType(is.blob(value), 'Blob', value),
nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* AssertionTypeDescription.nullOrUndefined */, value),
object: (value) => assertType(is.object(value), 'Object', value),
iterable: (value) => assertType(is.iterable(value), "Iterable" /* AssertionTypeDescription.iterable */, value),
asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* AssertionTypeDescription.asyncIterable */, value),
generator: (value) => assertType(is.generator(value), 'Generator', value),
asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value),
nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* AssertionTypeDescription.nativePromise */, value),
promise: (value) => assertType(is.promise(value), 'Promise', value),
generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value),
asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value),
// eslint-disable-next-line @typescript-eslint/ban-types
asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value),
// eslint-disable-next-line @typescript-eslint/ban-types
boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value),
regExp: (value) => assertType(is.regExp(value), 'RegExp', value),
date: (value) => assertType(is.date(value), 'Date', value),
error: (value) => assertType(is.error(value), 'Error', value),
map: (value) => assertType(is.map(value), 'Map', value),
set: (value) => assertType(is.set(value), 'Set', value),
weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value),
weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value),
weakRef: (value) => assertType(is.weakRef(value), 'WeakRef', value),
int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value),
uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value),
uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value),
int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value),
uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value),
int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value),
uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value),
float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value),
float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value),
bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value),
bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value),
arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value),
sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value),
dataView: (value) => assertType(is.dataView(value), 'DataView', value),
enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value),
urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value),
urlString: (value) => assertType(is.urlString(value), "string with a URL" /* AssertionTypeDescription.urlString */, value),
truthy: (value) => assertType(is.truthy(value), "truthy" /* AssertionTypeDescription.truthy */, value),
falsy: (value) => assertType(is.falsy(value), "falsy" /* AssertionTypeDescription.falsy */, value),
nan: (value) => assertType(is.nan(value), "NaN" /* AssertionTypeDescription.nan */, value),
primitive: (value) => assertType(is.primitive(value), "primitive" /* AssertionTypeDescription.primitive */, value),
integer: (value) => assertType(is.integer(value), "integer" /* AssertionTypeDescription.integer */, value),
safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* AssertionTypeDescription.safeInteger */, value),
plainObject: (value) => assertType(is.plainObject(value), "plain object" /* AssertionTypeDescription.plainObject */, value),
typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* AssertionTypeDescription.typedArray */, value),
arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* AssertionTypeDescription.arrayLike */, value),
tupleLike: (value, guards) => assertType(is.tupleLike(value, guards), "tuple-like" /* AssertionTypeDescription.tupleLike */, value),
domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* AssertionTypeDescription.domElement */, value),
observable: (value) => assertType(is.observable(value), 'Observable', value),
nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* AssertionTypeDescription.nodeStream */, value),
infinite: (value) => assertType(is.infinite(value), "infinite number" /* AssertionTypeDescription.infinite */, value),
emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* AssertionTypeDescription.emptyArray */, value),
nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* AssertionTypeDescription.nonEmptyArray */, value),
emptyString: (value) => assertType(is.emptyString(value), "empty string" /* AssertionTypeDescription.emptyString */, value),
emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* AssertionTypeDescription.emptyStringOrWhitespace */, value),
nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* AssertionTypeDescription.nonEmptyString */, value),
nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* AssertionTypeDescription.nonEmptyStringAndNotWhitespace */, value),
emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* AssertionTypeDescription.emptyObject */, value),
nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* AssertionTypeDescription.nonEmptyObject */, value),
emptySet: (value) => assertType(is.emptySet(value), "empty set" /* AssertionTypeDescription.emptySet */, value),
nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* AssertionTypeDescription.nonEmptySet */, value),
emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* AssertionTypeDescription.emptyMap */, value),
nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* AssertionTypeDescription.nonEmptyMap */, value),
propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value),
formData: (value) => assertType(is.formData(value), 'FormData', value),
urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value),
// Numbers.
evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* AssertionTypeDescription.evenInteger */, value),
oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* AssertionTypeDescription.oddInteger */, value),
// Two arguments.
directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* AssertionTypeDescription.directInstanceOf */, instance),
inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* AssertionTypeDescription.inRange */, value),
// Variadic functions.
any: (predicate, ...values) => assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* AssertionTypeDescription.any */, values, { multipleValues: true }),
all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* AssertionTypeDescription.all */, values, { multipleValues: true }),
};
/* eslint-enable @typescript-eslint/no-confusing-void-expression */
// Some few keywords are reserved, but we'll populate them for Node.js users
// See https://github.com/Microsoft/TypeScript/issues/2536
Object.defineProperties(is, {
class: {
value: is.class_,
},
function: {
value: is.function_,
},
null: {
value: is.null_,
},
});
Object.defineProperties(assert, {
class: {
value: assert.class_,
},
function: {
value: assert.function_,
},
null: {
value: assert.null_,
},
});
export default is;

View File

@@ -0,0 +1,32 @@
/**
Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
*/
export type Primitive = null | undefined | string | number | boolean | symbol | bigint;
/**
Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
*/
/**
Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
*/
export type Class<T = unknown, Arguments extends any[] = any[]> = new (...arguments_: Arguments) => T;
/**
Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
*/
export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
declare global {
interface SymbolConstructor {
readonly observable: symbol;
}
}
/**
Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
*/
export type ObservableLike = {
subscribe(observer: (value: unknown) => void): void;
[Symbol.observable](): ObservableLike;
};
export type Falsy = false | 0 | 0n | '' | null | undefined;
export type WeakRef<T extends object> = {
readonly [Symbol.toStringTag]: 'WeakRef';
deref(): T | undefined;
};

View File

@@ -0,0 +1,2 @@
// Extracted from https://github.com/sindresorhus/type-fest/blob/78019f42ea888b0cdceb41a4a78163868de57555/index.d.ts
export {};

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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.

View File

@@ -0,0 +1,76 @@
{
"name": "@sindresorhus/is",
"version": "5.6.0",
"description": "Type check values",
"license": "MIT",
"repository": "sindresorhus/is",
"funding": "https://github.com/sindresorhus/is?sponsor=1",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./dist/index.js",
"types": "./dist/index.d.ts",
"engines": {
"node": ">=14.16"
},
"scripts": {
"build": "del dist && tsc",
"test": "tsc --noEmit && xo && ava",
"prepare": "npm run build"
},
"files": [
"dist"
],
"keywords": [
"type",
"types",
"is",
"check",
"checking",
"validate",
"validation",
"utility",
"util",
"typeof",
"instanceof",
"object",
"assert",
"assertion",
"test",
"kind",
"primitive",
"verify",
"compare",
"typescript",
"typeguards",
"types"
],
"devDependencies": {
"@sindresorhus/tsconfig": "^3.0.1",
"@types/jsdom": "^21.1.1",
"@types/node": "^20.2.5",
"@types/zen-observable": "^0.8.3",
"ava": "^5.3.0",
"del-cli": "^5.0.0",
"jsdom": "^20.0.1",
"rxjs": "^7.8.1",
"tempy": "^3.0.0",
"ts-node": "^10.9.1",
"typescript": "^5.0.4",
"xo": "^0.54.2",
"zen-observable": "^0.10.0",
"expect-type": "^0.16.0"
},
"sideEffects": false,
"ava": {
"extensions": {
"ts": "module"
},
"nodeArguments": [
"--loader=ts-node/esm"
]
}
}

View File

@@ -0,0 +1,698 @@
# is
> Type check values
For example, `is.string('🦄') //=> true`
<img src="header.gif" width="182" align="right">
## Highlights
- Written in TypeScript
- [Extensive use of type guards](#type-guards)
- [Supports type assertions](#type-assertions)
- [Aware of generic type parameters](#generic-type-parameters) (use with caution)
- Actively maintained
- ![Millions of downloads per week](https://img.shields.io/npm/dw/@sindresorhus/is)
## Install
```sh
npm install @sindresorhus/is
```
## Usage
```js
import is from '@sindresorhus/is';
is('🦄');
//=> 'string'
is(new Map());
//=> 'Map'
is.number(6);
//=> true
```
[Assertions](#type-assertions) perform the same type checks, but throw an error if the type does not match.
```js
import {assert} from '@sindresorhus/is';
assert.string(2);
//=> Error: Expected value which is `string`, received value of type `number`.
```
And with TypeScript:
```ts
import {assert} from '@sindresorhus/is';
assert.string(foo);
// `foo` is now typed as a `string`.
```
## API
### is(value)
Returns the type of `value`.
Primitives are lowercase and object types are camelcase.
Example:
- `'undefined'`
- `'null'`
- `'string'`
- `'symbol'`
- `'Array'`
- `'Function'`
- `'Object'`
Note: It will throw an error if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`.
### is.{method}
All the below methods accept a value and returns a boolean for whether the value is of the desired type.
#### Primitives
##### .undefined(value)
##### .null(value)
**Note:** TypeScript users must use `.null_()` because of a TypeScript naming limitation.
##### .string(value)
##### .number(value)
Note: `is.number(NaN)` returns `false`. This intentionally deviates from `typeof` behavior to increase user-friendliness of `is` type checks.
##### .boolean(value)
##### .symbol(value)
##### .bigint(value)
#### Built-in types
##### .array(value, assertion?)
Returns true if `value` is an array and all of its items match the assertion (if provided).
```js
is.array(value); // Validate `value` is an array.
is.array(value, is.number); // Validate `value` is an array and all of its items are numbers.
```
##### .function(value)
**Note:** TypeScript users must use `.function_()` because of a TypeScript naming limitation.
##### .buffer(value)
##### .blob(value)
##### .object(value)
Keep in mind that [functions are objects too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions).
##### .numericString(value)
Returns `true` for a string that represents a number satisfying `is.number`, for example, `'42'` and `'-8.3'`.
Note: `'NaN'` returns `false`, but `'Infinity'` and `'-Infinity'` return `true`.
##### .regExp(value)
##### .date(value)
##### .error(value)
##### .nativePromise(value)
##### .promise(value)
Returns `true` for any object with a `.then()` and `.catch()` method. Prefer this one over `.nativePromise()` as you usually want to allow userland promise implementations too.
##### .generator(value)
Returns `true` for any object that implements its own `.next()` and `.throw()` methods and has a function definition for `Symbol.iterator`.
##### .generatorFunction(value)
##### .asyncFunction(value)
Returns `true` for any `async` function that can be called with the `await` operator.
```js
is.asyncFunction(async () => {});
//=> true
is.asyncFunction(() => {});
//=> false
```
##### .asyncGenerator(value)
```js
is.asyncGenerator(
(async function * () {
yield 4;
})()
);
//=> true
is.asyncGenerator(
(function * () {
yield 4;
})()
);
//=> false
```
##### .asyncGeneratorFunction(value)
```js
is.asyncGeneratorFunction(async function * () {
yield 4;
});
//=> true
is.asyncGeneratorFunction(function * () {
yield 4;
});
//=> false
```
##### .boundFunction(value)
Returns `true` for any `bound` function.
```js
is.boundFunction(() => {});
//=> true
is.boundFunction(function () {}.bind(null));
//=> true
is.boundFunction(function () {});
//=> false
```
##### .map(value)
##### .set(value)
##### .weakMap(value)
##### .weakSet(value)
##### .weakRef(value)
#### Typed arrays
##### .int8Array(value)
##### .uint8Array(value)
##### .uint8ClampedArray(value)
##### .int16Array(value)
##### .uint16Array(value)
##### .int32Array(value)
##### .uint32Array(value)
##### .float32Array(value)
##### .float64Array(value)
##### .bigInt64Array(value)
##### .bigUint64Array(value)
#### Structured data
##### .arrayBuffer(value)
##### .sharedArrayBuffer(value)
##### .dataView(value)
##### .enumCase(value, enum)
TypeScript-only. Returns `true` if `value` is a member of `enum`.
```ts
enum Direction {
Ascending = 'ascending',
Descending = 'descending'
}
is.enumCase('ascending', Direction);
//=> true
is.enumCase('other', Direction);
//=> false
```
#### Emptiness
##### .emptyString(value)
Returns `true` if the value is a `string` and the `.length` is 0.
##### .emptyStringOrWhitespace(value)
Returns `true` if `is.emptyString(value)` or if it's a `string` that is all whitespace.
##### .nonEmptyString(value)
Returns `true` if the value is a `string` and the `.length` is more than 0.
##### .nonEmptyStringAndNotWhitespace(value)
Returns `true` if the value is a `string` that is not empty and not whitespace.
```js
const values = ['property1', '', null, 'property2', ' ', undefined];
values.filter(is.nonEmptyStringAndNotWhitespace);
//=> ['property1', 'property2']
```
##### .emptyArray(value)
Returns `true` if the value is an `Array` and the `.length` is 0.
##### .nonEmptyArray(value)
Returns `true` if the value is an `Array` and the `.length` is more than 0.
##### .emptyObject(value)
Returns `true` if the value is an `Object` and `Object.keys(value).length` is 0.
Please note that `Object.keys` returns only own enumerable properties. Hence something like this can happen:
```js
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: true,
enumerable: false,
configurable: true
});
is.emptyObject(object1);
//=> true
```
##### .nonEmptyObject(value)
Returns `true` if the value is an `Object` and `Object.keys(value).length` is more than 0.
##### .emptySet(value)
Returns `true` if the value is a `Set` and the `.size` is 0.
##### .nonEmptySet(Value)
Returns `true` if the value is a `Set` and the `.size` is more than 0.
##### .emptyMap(value)
Returns `true` if the value is a `Map` and the `.size` is 0.
##### .nonEmptyMap(value)
Returns `true` if the value is a `Map` and the `.size` is more than 0.
#### Miscellaneous
##### .directInstanceOf(value, class)
Returns `true` if `value` is a direct instance of `class`.
```js
is.directInstanceOf(new Error(), Error);
//=> true
class UnicornError extends Error {}
is.directInstanceOf(new UnicornError(), Error);
//=> false
```
##### .urlInstance(value)
Returns `true` if `value` is an instance of the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL).
```js
const url = new URL('https://example.com');
is.urlInstance(url);
//=> true
```
##### .urlString(value)
Returns `true` if `value` is a URL string.
Note: this only does basic checking using the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor.
```js
const url = 'https://example.com';
is.urlString(url);
//=> true
is.urlString(new URL(url));
//=> false
```
##### .truthy(value)
Returns `true` for all values that evaluate to true in a boolean context:
```js
is.truthy('🦄');
//=> true
is.truthy(undefined);
//=> false
```
##### .falsy(value)
Returns `true` if `value` is one of: `false`, `0`, `''`, `null`, `undefined`, `NaN`.
##### .nan(value)
##### .nullOrUndefined(value)
##### .primitive(value)
JavaScript primitives are as follows: `null`, `undefined`, `string`, `number`, `boolean`, `symbol`.
##### .integer(value)
##### .safeInteger(value)
Returns `true` if `value` is a [safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
##### .plainObject(value)
An object is plain if it's created by either `{}`, `new Object()`, or `Object.create(null)`.
##### .iterable(value)
##### .asyncIterable(value)
##### .class(value)
Returns `true` for instances created by a class.
**Note:** TypeScript users must use `.class_()` because of a TypeScript naming limitation.
##### .typedArray(value)
##### .arrayLike(value)
A `value` is array-like if it is not a function and has a `value.length` that is a safe integer greater than or equal to 0.
```js
is.arrayLike(document.forms);
//=> true
function foo() {
is.arrayLike(arguments);
//=> true
}
foo();
```
##### .tupleLike(value, guards)
A `value` is tuple-like if it matches the provided `guards` array both in `.length` and in types.
```js
is.tupleLike([1], [is.number]);
//=> true
```
```js
function foo() {
const tuple = [1, '2', true];
if (is.tupleLike(tuple, [is.number, is.string, is.boolean])) {
tuple // [number, string, boolean]
}
}
foo();
```
#### .positiveNumber(value)
Check if `value` is a number and is more than 0.
#### .negativeNumber(value)
Check if `value` is a number and is less than 0.
##### .inRange(value, range)
Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order.
```js
is.inRange(3, [0, 5]);
is.inRange(3, [5, 0]);
is.inRange(0, [-2, 2]);
```
##### .inRange(value, upperBound)
Check if `value` (number) is in the range of `0` to `upperBound`.
```js
is.inRange(3, 10);
```
##### .domElement(value)
Returns `true` if `value` is a DOM Element.
##### .nodeStream(value)
Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html).
```js
import fs from 'node:fs';
is.nodeStream(fs.createReadStream('unicorn.png'));
//=> true
```
##### .observable(value)
Returns `true` if `value` is an `Observable`.
```js
import {Observable} from 'rxjs';
is.observable(new Observable());
//=> true
```
##### .infinite(value)
Check if `value` is `Infinity` or `-Infinity`.
##### .evenInteger(value)
Returns `true` if `value` is an even integer.
##### .oddInteger(value)
Returns `true` if `value` is an odd integer.
##### .propertyKey(value)
Returns `true` if `value` can be used as an object property key (either `string`, `number`, or `symbol`).
##### .formData(value)
Returns `true` if `value` is an instance of the [`FormData` class](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
```js
const data = new FormData();
is.formData(data);
//=> true
```
##### .urlSearchParams(value)
Returns `true` if `value` is an instance of the [`URLSearchParams` class](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).
```js
const searchParams = new URLSearchParams();
is.urlSearchParams(searchParams);
//=> true
```
##### .any(predicate | predicate[], ...values)
Using a single `predicate` argument, returns `true` if **any** of the input `values` returns true in the `predicate`:
```js
is.any(is.string, {}, true, '🦄');
//=> true
is.any(is.boolean, 'unicorns', [], new Map());
//=> false
```
Using an array of `predicate[]`, returns `true` if **any** of the input `values` returns true for **any** of the `predicates` provided in an array:
```js
is.any([is.string, is.number], {}, true, '🦄');
//=> true
is.any([is.boolean, is.number], 'unicorns', [], new Map());
//=> false
```
##### .all(predicate, ...values)
Returns `true` if **all** of the input `values` returns true in the `predicate`:
```js
is.all(is.object, {}, new Map(), new Set());
//=> true
is.all(is.string, '🦄', [], 'unicorns');
//=> false
```
## Type guards
When using `is` together with TypeScript, [type guards](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) are being used extensively to infer the correct type inside if-else statements.
```ts
import is from '@sindresorhus/is';
const padLeft = (value: string, padding: string | number) => {
if (is.number(padding)) {
// `padding` is typed as `number`
return Array(padding + 1).join(' ') + value;
}
if (is.string(padding)) {
// `padding` is typed as `string`
return padding + value;
}
throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`);
}
padLeft('🦄', 3);
//=> ' 🦄'
padLeft('🦄', '🌈');
//=> '🌈🦄'
```
## Type assertions
The type guards are also available as [type assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions), which throw an error for unexpected types. It is a convenient one-line version of the often repetitive "if-not-expected-type-throw" pattern.
```ts
import {assert} from '@sindresorhus/is';
const handleMovieRatingApiResponse = (response: unknown) => {
assert.plainObject(response);
// `response` is now typed as a plain `object` with `unknown` properties.
assert.number(response.rating);
// `response.rating` is now typed as a `number`.
assert.string(response.title);
// `response.title` is now typed as a `string`.
return `${response.title} (${response.rating * 10})`;
};
handleMovieRatingApiResponse({rating: 0.87, title: 'The Matrix'});
//=> 'The Matrix (8.7)'
// This throws an error.
handleMovieRatingApiResponse({rating: '🦄'});
```
## Generic type parameters
The type guards and type assertions are aware of [generic type parameters](https://www.typescriptlang.org/docs/handbook/generics.html), such as `Promise<T>` and `Map<Key, Value>`. The default is `unknown` for most cases, since `is` cannot check them at runtime. If the generic type is known at compile-time, either implicitly (inferred) or explicitly (provided), `is` propagates the type so it can be used later.
Use generic type parameters with caution. They are only checked by the TypeScript compiler, and not checked by `is` at runtime. This can lead to unexpected behavior, where the generic type is _assumed_ at compile-time, but actually is something completely different at runtime. It is best to use `unknown` (default) and type-check the value of the generic type parameter at runtime with `is` or `assert`.
```ts
import {assert} from '@sindresorhus/is';
async function badNumberAssumption(input: unknown) {
// Bad assumption about the generic type parameter fools the compile-time type system.
assert.promise<number>(input);
// `input` is a `Promise` but only assumed to be `Promise<number>`.
const resolved = await input;
// `resolved` is typed as `number` but was not actually checked at runtime.
// Multiplication will return NaN if the input promise did not actually contain a number.
return 2 * resolved;
}
async function goodNumberAssertion(input: unknown) {
assert.promise(input);
// `input` is typed as `Promise<unknown>`
const resolved = await input;
// `resolved` is typed as `unknown`
assert.number(resolved);
// `resolved` is typed as `number`
// Uses runtime checks so only numbers will reach the multiplication.
return 2 * resolved;
}
badNumberAssumption(Promise.resolve('An unexpected string'));
//=> NaN
// This correctly throws an error because of the unexpected string value.
goodNumberAssertion(Promise.resolve('An unexpected string'));
```
## FAQ
### Why yet another type checking module?
There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs:
- Includes both type methods and ability to get the type
- Types of primitives returned as lowercase and object types as camelcase
- Covers all built-ins
- Unsurprising behavior
- Well-maintained
- Comprehensive test suite
For the ones I found, pick 3 of these.
The most common mistakes I noticed in these modules was using `instanceof` for type checking, forgetting that functions are objects, and omitting `symbol` as a primitive.
### Why not just use `instanceof` instead of this package?
`instanceof` does not work correctly for all types and it does not work across [realms](https://stackoverflow.com/a/49832343/64949). Examples of realms are iframes, windows, web workers, and the `vm` module in Node.js.
## For enterprise
Available as part of the Tidelift Subscription.
The maintainers of @sindresorhus/is and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-sindresorhus-is?utm_source=npm-sindresorhus-is&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [ow](https://github.com/sindresorhus/ow) - Function argument validation for humans
- [is-stream](https://github.com/sindresorhus/is-stream) - Check if something is a Node.js stream
- [is-observable](https://github.com/sindresorhus/is-observable) - Check if a value is an Observable
- [file-type](https://github.com/sindresorhus/file-type) - Detect the file type of a Buffer/Uint8Array
- [is-ip](https://github.com/sindresorhus/is-ip) - Check if a string is an IP address
- [is-array-sorted](https://github.com/sindresorhus/is-array-sorted) - Check if an Array is sorted
- [is-error-constructor](https://github.com/sindresorhus/is-error-constructor) - Check if a value is an error constructor
- [is-empty-iterable](https://github.com/sindresorhus/is-empty-iterable) - Check if an Iterable is empty
- [is-blob](https://github.com/sindresorhus/is-blob) - Check if a value is a Blob - File-like object of immutable, raw data
- [has-emoji](https://github.com/sindresorhus/has-emoji) - Check whether a string has any emoji
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Giora Guttsait](https://github.com/gioragutt)
- [Brandon Smith](https://github.com/brandon93s)

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

@@ -0,0 +1,154 @@
{
"name": "got",
"version": "12.6.1",
"description": "Human-friendly and powerful HTTP request library for Node.js",
"license": "MIT",
"repository": "sindresorhus/got",
"funding": "https://github.com/sindresorhus/got?sponsor=1",
"type": "module",
"exports": "./dist/source/index.js",
"types": "./dist/source/index.d.ts",
"engines": {
"node": ">=14.16"
},
"scripts": {
"test": "xo && tsc --noEmit && 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": "^5.2.0",
"@szmarczak/http-timer": "^5.0.1",
"cacheable-lookup": "^7.0.0",
"cacheable-request": "^10.2.8",
"decompress-response": "^6.0.0",
"form-data-encoder": "^2.1.2",
"get-stream": "^6.0.1",
"http2-wrapper": "^2.1.10",
"lowercase-keys": "^3.0.0",
"p-cancelable": "^3.0.0",
"responselike": "^3.0.0"
},
"devDependencies": {
"@hapi/bourne": "^3.0.0",
"@sindresorhus/tsconfig": "^3.0.1",
"@sinonjs/fake-timers": "^10.0.2",
"@types/benchmark": "^2.1.2",
"@types/express": "^4.17.17",
"@types/node": "^18.14.5",
"@types/pem": "^1.9.6",
"@types/pify": "^5.0.1",
"@types/readable-stream": "^2.3.13",
"@types/request": "^2.48.8",
"@types/sinon": "^10.0.11",
"@types/sinonjs__fake-timers": "^8.1.1",
"@types/tough-cookie": "^4.0.1",
"ava": "^5.2.0",
"axios": "^0.27.2",
"benchmark": "^2.1.4",
"bluebird": "^3.7.2",
"body-parser": "^1.20.2",
"create-cert": "^1.0.6",
"create-test-server": "^3.0.1",
"del-cli": "^5.0.0",
"delay": "^5.0.0",
"express": "^4.17.3",
"form-data": "^4.0.0",
"formdata-node": "^5.0.0",
"nock": "^13.3.0",
"node-fetch": "^3.2.3",
"np": "^7.6.0",
"nyc": "^15.1.0",
"p-event": "^5.0.1",
"pem": "^1.14.6",
"pify": "^6.0.0",
"readable-stream": "^4.2.0",
"request": "^2.88.2",
"sinon": "^15.0.1",
"slow-stream": "0.0.4",
"tempy": "^3.0.0",
"then-busboy": "^5.2.1",
"tough-cookie": "4.1.2",
"ts-node": "^10.8.2",
"type-fest": "^3.6.1",
"typescript": "~4.9.5",
"xo": "^0.53.1"
},
"sideEffects": false,
"ava": {
"files": [
"test/*"
],
"timeout": "1m",
"extensions": {
"ts": "module"
},
"nodeArguments": [
"--loader=ts-node/esm"
]
},
"nyc": {
"reporter": [
"text",
"html",
"lcov"
],
"extension": [
".ts"
],
"exclude": [
"**/test/**"
]
},
"xo": {
"ignores": [
"documentation/examples/*"
],
"rules": {
"@typescript-eslint/no-empty-function": "off",
"n/no-deprecated-api": "off",
"n/prefer-global/url": "off",
"n/prefer-global/url-search-params": "off",
"@typescript-eslint/no-implicit-any-catch": "off",
"unicorn/prefer-node-protocol": "off",
"ava/assertion-arguments": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/no-redundant-type-constituents": "off",
"no-lone-blocks": "off",
"unicorn/no-await-expression-member": "off"
}
},
"runkitExampleFilename": "./documentation/examples/runkit-example.js"
}

527
node_modules/got/readme.md generated vendored Normal file
View File

@@ -0,0 +1,527 @@
<div align="center">
<br>
<br>
<img width="360" src="media/logo.svg" alt="Got">
<br>
<br>
<br>
<p>
<p>
<sup>
Sindre's open source work is supported by the community.<br>Special thanks to:
</sup>
</p>
<br>
<a href="https://retool.com/?utm_campaign=sindresorhus">
<img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="210">
</a>
<br>
<br>
<a href="https://strapi.io/?ref=sindresorhus">
<div>
<img src="https://sindresorhus.com/assets/thanks/strapi-logo-white-bg.png" width="200" alt="Strapi">
</div>
<b>Strapi is the leading open-source headless CMS.</b>
<div>
<sup>Its 100% JavaScript, fully customizable, and developer-first.</sup>
</div>
</a>
<br>
<br>
<br>
<a href="https://serpapi.com#gh-light-mode-only">
<div>
<img src="https://sindresorhus.com/assets/thanks/serpapi-logo-light.svg" width="130" alt="SerpApi">
</div>
<b>API to get search engine results with ease.</b>
</a>
<a href="https://serpapi.com#gh-dark-mode-only">
<div>
<img src="https://sindresorhus.com/assets/thanks/serpapi-logo-dark.svg" width="120" alt="SerpApi">
</div>
<b>API to get search engine results with ease.</b>
</a>
<br>
<br>
<br>
<br>
<a href="https://dutchis.net/?ref=sindresorhus#gh-light-mode-only">
<div>
<img src="https://sindresorhus.com/assets/thanks/dutchis-logo-light.png" width="200" alt="DutchIS">
</div>
<br>
<b>VPS hosting with taste 😛</b>
</a>
<a href="https://dutchis.net/?ref=sindresorhus#gh-dark-mode-only">
<div>
<img src="https://sindresorhus.com/assets/thanks/dutchis-logo-dark.png" width="200" alt="DutchIS">
</div>
<br>
<b>VPS hosting with taste 😛</b>
</a>
<br>
<br>
<br>
<br>
<br>
<br>
</p>
<br>
<br>
</div>
> Human-friendly and powerful HTTP request library for Node.js
<!-- [![Coverage Status](https://codecov.io/gh/sindresorhus/got/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/got/branch/main) -->
[![Downloads](https://img.shields.io/npm/dm/got.svg)](https://npmjs.com/got)
[![Install size](https://packagephobia.com/badge?p=got)](https://packagephobia.com/result?p=got)
[See how Got compares to other HTTP libraries](#comparison)
---
For browser usage, we recommend [Ky](https://github.com/sindresorhus/ky) by the same people.
---
**Support questions should be asked [here](https://github.com/sindresorhus/got/discussions).**
## Install
```sh
npm install got
```
**Warning:** This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) or use the [dynamic `import()`](https://v8.dev/features/dynamic-import) function. Please don't open issues for questions regarding CommonJS / ESM.
**Got v11 (the previous major version) is no longer maintained and we will not accept any backport requests.**
## Take a peek
**A [quick start](documentation/quick-start.md) guide is available.**
### JSON mode
Got has a dedicated option for handling JSON payload.\
Furthermore, the promise exposes a `.json<T>()` function that returns `Promise<T>`.
```js
import got from 'got';
const {data} = await got.post('https://httpbin.org/anything', {
json: {
hello: 'world'
}
}).json();
console.log(data);
//=> {"hello": "world"}
```
For advanced JSON usage, check out the [`parseJson`](documentation/2-options.md#parsejson) and [`stringifyJson`](documentation/2-options.md#stringifyjson) options.
**For more useful tips like this, visit the [Tips](documentation/tips.md) page.**
## Highlights
- [Used by 8K+ packages and 4M+ repos](https://github.com/sindresorhus/got/network/dependents)
- [Actively maintained](https://github.com/sindresorhus/got/graphs/contributors)
- [Trusted by many companies](#widely-used)
## Documentation
By default, Got will retry on failure. To disable this option, set [`options.retry.limit`](documentation/7-retry.md#retry) to 0.
#### Main API
- [x] [Promise API](documentation/1-promise.md)
- [x] [Options](documentation/2-options.md)
- [x] [Stream API](documentation/3-streams.md)
- [x] [Pagination API](documentation/4-pagination.md)
- [x] [Advanced HTTPS API](documentation/5-https.md)
- [x] [HTTP/2 support](documentation/2-options.md#http2)
- [x] [`Response` class](documentation/3-streams.md#response-2)
#### Timeouts and retries
- [x] [Advanced timeout handling](documentation/6-timeout.md)
- [x] [Retries on failure](documentation/7-retry.md)
- [x] [Errors with metadata](documentation/8-errors.md)
#### Advanced creation
- [x] [Hooks](documentation/9-hooks.md)
- [x] [Instances](documentation/10-instances.md)
- [x] [Progress events & other events](documentation/3-streams.md#events)
- [x] [Plugins](documentation/lets-make-a-plugin.md)
- [x] [Compose](documentation/examples/advanced-creation.js)
#### Cache, Proxy and UNIX sockets
- [x] [RFC compliant caching](documentation/cache.md)
- [x] [Proxy support](documentation/tips.md#proxying)
- [x] [Unix Domain Sockets](documentation/2-options.md#enableunixsockets)
#### Integration
- [x] [TypeScript support](documentation/typescript.md)
- [x] [AWS](documentation/tips.md#aws)
- [x] [Testing](documentation/tips.md#testing)
---
### Migration guides
- [Request migration guide](documentation/migration-guides/request.md)
- [*(Note that Request is unmaintained)*](https://github.com/request/request/issues/3142)
- [Axios](documentation/migration-guides/axios.md)
- [Node.js](documentation/migration-guides/nodejs.md)
## Got plugins
- [`got4aws`](https://github.com/SamVerschueren/got4aws) - Got convenience wrapper to interact with AWS v4 signed APIs
- [`gh-got`](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API
- [`gl-got`](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API
- [`gotql`](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings
- [`got-fetch`](https://github.com/alexghr/got-fetch) - Got with a [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) interface
- [`got-scraping`](https://github.com/apify/got-scraping) - Got wrapper specifically designed for web scraping purposes
- [`got-ssrf`](https://github.com/JaneJeon/got-ssrf) - Got wrapper to protect server-side requests against SSRF attacks
### Legacy
- [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API
- [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL
## Comparison
| | `got` | [`node-fetch`][n0] | [`ky`][k0] | [`axios`][a0] | [`superagent`][s0] |
|-----------------------|:-------------------:|:--------------------:|:------------------------:|:------------------:|:----------------------:|
| HTTP/2 support | :heavy_check_mark:¹ | :x: | :x: | :x: | :heavy_check_mark:\*\* |
| Browser support | :x: | :heavy_check_mark:\* | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Promise API | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Stream API | :heavy_check_mark: | Node.js only | :x: | :x: | :heavy_check_mark: |
| Pagination API | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Request cancelation | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| RFC compliant caching | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Cookies (out-of-box) | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Follows redirects | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Retries on failure | :heavy_check_mark: | :x: | :heavy_check_mark: | :x: | :heavy_check_mark: |
| Progress events | :heavy_check_mark: | :x: | :heavy_check_mark:\*\*\* | Browser only | :heavy_check_mark: |
| Handles gzip/deflate | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Advanced timeouts | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Timings | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Errors with metadata | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: |
| JSON mode | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Custom defaults | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: |
| Composable | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: |
| Hooks | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: |
| Issues open | [![][gio]][g1] | [![][nio]][n1] | [![][kio]][k1] | [![][aio]][a1] | [![][sio]][s1] |
| Issues closed | [![][gic]][g2] | [![][nic]][n2] | [![][kic]][k2] | [![][aic]][a2] | [![][sic]][s2] |
| Downloads | [![][gd]][g3] | [![][nd]][n3] | [![][kd]][k3] | [![][ad]][a3] | [![][sd]][s3] |
| Coverage | TBD | [![][nc]][n4] | [![][kc]][k4] | [![][ac]][a4] | [![][sc]][s4] |
| Build | [![][gb]][g5] | [![][nb]][n5] | [![][kb]][k5] | [![][ab]][a5] | [![][sb]][s5] |
| Bugs | [![][gbg]][g6] | [![][nbg]][n6] | [![][kbg]][k6] | [![][abg]][a6] | [![][sbg]][s6] |
| Dependents | [![][gdp]][g7] | [![][ndp]][n7] | [![][kdp]][k7] | [![][adp]][a7] | [![][sdp]][s7] |
| Install size | [![][gis]][g8] | [![][nis]][n8] | [![][kis]][k8] | [![][ais]][a8] | [![][sis]][s8] |
| GitHub stars | [![][gs]][g9] | [![][ns]][n9] | [![][ks]][k9] | [![][as]][a9] | [![][ss]][s9] |
| TypeScript support | [![][gts]][g10] | [![][nts]][n10] | [![][kts]][k10] | [![][ats]][a10] | [![][sts]][s11] |
| Last commit | [![][glc]][g11] | [![][nlc]][n11] | [![][klc]][k11] | [![][alc]][a11] | [![][slc]][s11] |
\* It's almost API compatible with the browser `fetch` API.\
\*\* Need to switch the protocol manually. Doesn't accept PUSH streams and doesn't reuse HTTP/2 sessions.\
\*\*\* Currently, only `DownloadProgress` event is supported, `UploadProgress` event is not supported.\
¹ Requires Node.js 15.10.0 or above.\
:sparkle: Almost-stable feature, but the API may change. Don't hesitate to try it out!\
:grey_question: Feature in early stage of development. Very experimental.
<!-- GITHUB -->
[k0]: https://github.com/sindresorhus/ky
[n0]: https://github.com/node-fetch/node-fetch
[a0]: https://github.com/axios/axios
[s0]: https://github.com/visionmedia/superagent
<!-- ISSUES OPEN -->
[gio]: https://img.shields.io/github/issues-raw/sindresorhus/got?color=gray&label
[kio]: https://img.shields.io/github/issues-raw/sindresorhus/ky?color=gray&label
[nio]: https://img.shields.io/github/issues-raw/bitinn/node-fetch?color=gray&label
[aio]: https://img.shields.io/github/issues-raw/axios/axios?color=gray&label
[sio]: https://img.shields.io/github/issues-raw/visionmedia/superagent?color=gray&label
[g1]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[k1]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[n1]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[a1]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[s1]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
<!-- ISSUES CLOSED -->
[gic]: https://img.shields.io/github/issues-closed-raw/sindresorhus/got?color=blue&label
[kic]: https://img.shields.io/github/issues-closed-raw/sindresorhus/ky?color=blue&label
[nic]: https://img.shields.io/github/issues-closed-raw/bitinn/node-fetch?color=blue&label
[aic]: https://img.shields.io/github/issues-closed-raw/axios/axios?color=blue&label
[sic]: https://img.shields.io/github/issues-closed-raw/visionmedia/superagent?color=blue&label
[g2]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[k2]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[n2]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[a2]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[s2]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
<!-- DOWNLOADS -->
[gd]: https://img.shields.io/npm/dm/got?color=darkgreen&label
[kd]: https://img.shields.io/npm/dm/ky?color=darkgreen&label
[nd]: https://img.shields.io/npm/dm/node-fetch?color=darkgreen&label
[ad]: https://img.shields.io/npm/dm/axios?color=darkgreen&label
[sd]: https://img.shields.io/npm/dm/superagent?color=darkgreen&label
[g3]: https://www.npmjs.com/package/got
[k3]: https://www.npmjs.com/package/ky
[n3]: https://www.npmjs.com/package/node-fetch
[a3]: https://www.npmjs.com/package/axios
[s3]: https://www.npmjs.com/package/superagent
<!-- COVERAGE -->
[gc]: https://img.shields.io/coveralls/github/sindresorhus/got?color=0b9062&label
[kc]: https://img.shields.io/codecov/c/github/sindresorhus/ky?color=0b9062&label
[nc]: https://img.shields.io/coveralls/github/bitinn/node-fetch?color=0b9062&label
[ac]: https://img.shields.io/coveralls/github/mzabriskie/axios?color=0b9062&label
[sc]: https://img.shields.io/codecov/c/github/visionmedia/superagent?color=0b9062&label
[g4]: https://coveralls.io/github/sindresorhus/got
[k4]: https://codecov.io/gh/sindresorhus/ky
[n4]: https://coveralls.io/github/bitinn/node-fetch
[a4]: https://coveralls.io/github/mzabriskie/axios
[s4]: https://codecov.io/gh/visionmedia/superagent
<!-- BUILD -->
[gb]: https://github.com/sindresorhus/got/actions/workflows/main.yml/badge.svg
[kb]: https://github.com/sindresorhus/ky/actions/workflows/main.yml/badge.svg
[nb]: https://img.shields.io/travis/bitinn/node-fetch?label
[ab]: https://img.shields.io/travis/axios/axios?label
[sb]: https://img.shields.io/travis/visionmedia/superagent?label
[g5]: https://github.com/sindresorhus/got/actions/workflows/main.yml
[k5]: https://github.com/sindresorhus/ky/actions/workflows/main.yml
[n5]: https://travis-ci.org/github/bitinn/node-fetch
[a5]: https://travis-ci.org/github/axios/axios
[s5]: https://travis-ci.org/github/visionmedia/superagent
<!-- BUGS -->
[gbg]: https://img.shields.io/github/issues-raw/sindresorhus/got/bug?color=darkred&label
[kbg]: https://img.shields.io/github/issues-raw/sindresorhus/ky/bug?color=darkred&label
[nbg]: https://img.shields.io/github/issues-raw/bitinn/node-fetch/bug?color=darkred&label
[abg]: https://img.shields.io/github/issues-raw/axios/axios/bug-fix?color=darkred&label
[sbg]: https://img.shields.io/github/issues-raw/visionmedia/superagent/Bug?color=darkred&label
[g6]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug
[k6]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug
[n6]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug
[a6]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22bug-fix%22
[s6]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3ABug
<!-- DEPENDENTS -->
[gdp]: https://badgen.net/npm/dependents/got?color=orange&label
[kdp]: https://badgen.net/npm/dependents/ky?color=orange&label
[ndp]: https://badgen.net/npm/dependents/node-fetch?color=orange&label
[adp]: https://badgen.net/npm/dependents/axios?color=orange&label
[sdp]: https://badgen.net/npm/dependents/superagent?color=orange&label
[g7]: https://www.npmjs.com/package/got?activeTab=dependents
[k7]: https://www.npmjs.com/package/ky?activeTab=dependents
[n7]: https://www.npmjs.com/package/node-fetch?activeTab=dependents
[a7]: https://www.npmjs.com/package/axios?activeTab=dependents
[s7]: https://www.npmjs.com/package/visionmedia?activeTab=dependents
<!-- INSTALL SIZE -->
[gis]: https://badgen.net/packagephobia/install/got?color=blue&label
[kis]: https://badgen.net/packagephobia/install/ky?color=blue&label
[nis]: https://badgen.net/packagephobia/install/node-fetch?color=blue&label
[ais]: https://badgen.net/packagephobia/install/axios?color=blue&label
[sis]: https://badgen.net/packagephobia/install/superagent?color=blue&label
[g8]: https://packagephobia.com/result?p=got
[k8]: https://packagephobia.com/result?p=ky
[n8]: https://packagephobia.com/result?p=node-fetch
[a8]: https://packagephobia.com/result?p=axios
[s8]: https://packagephobia.com/result?p=superagent
<!-- GITHUB STARS -->
[gs]: https://img.shields.io/github/stars/sindresorhus/got?color=white&label
[ks]: https://img.shields.io/github/stars/sindresorhus/ky?color=white&label
[ns]: https://img.shields.io/github/stars/bitinn/node-fetch?color=white&label
[as]: https://img.shields.io/github/stars/axios/axios?color=white&label
[ss]: https://img.shields.io/github/stars/visionmedia/superagent?color=white&label
[g9]: https://github.com/sindresorhus/got
[k9]: https://github.com/sindresorhus/ky
[n9]: https://github.com/node-fetch/node-fetch
[a9]: https://github.com/axios/axios
[s9]: https://github.com/visionmedia/superagent
<!-- TYPESCRIPT SUPPORT -->
[gts]: https://badgen.net/npm/types/got?label
[kts]: https://badgen.net/npm/types/ky?label
[nts]: https://badgen.net/npm/types/node-fetch?label
[ats]: https://badgen.net/npm/types/axios?label
[sts]: https://badgen.net/npm/types/superagent?label
[g10]: https://github.com/sindresorhus/got
[k10]: https://github.com/sindresorhus/ky
[n10]: https://github.com/node-fetch/node-fetch
[a10]: https://github.com/axios/axios
[s10]: https://github.com/visionmedia/superagent
<!-- LAST COMMIT -->
[glc]: https://img.shields.io/github/last-commit/sindresorhus/got?color=gray&label
[klc]: https://img.shields.io/github/last-commit/sindresorhus/ky?color=gray&label
[nlc]: https://img.shields.io/github/last-commit/bitinn/node-fetch?color=gray&label
[alc]: https://img.shields.io/github/last-commit/axios/axios?color=gray&label
[slc]: https://img.shields.io/github/last-commit/visionmedia/superagent?color=gray&label
[g11]: https://github.com/sindresorhus/got/commits
[k11]: https://github.com/sindresorhus/ky/commits
[n11]: https://github.com/node-fetch/node-fetch/commits
[a11]: https://github.com/axios/axios/commits
[s11]: https://github.com/visionmedia/superagent/commits
[Click here][InstallSizeOfTheDependencies] to see the install size of the Got dependencies.
[InstallSizeOfTheDependencies]: https://packagephobia.com/result?p=@sindresorhus/is@4.0.1,@szmarczak/http-timer@4.0.5,@types/cacheable-request@6.0.1,@types/responselike@1.0.0,cacheable-lookup@6.0.0,cacheable-request@7.0.2,decompress-response@6.0.0,get-stream@6.0.1,http2-wrapper@2.0.5,lowercase-keys@2.0.0,p-cancelable@2.1.1,responselike@2.0.0
## Maintainers
[![Sindre Sorhus](https://github.com/sindresorhus.png?size=100)](https://sindresorhus.com) | [![Szymon Marczak](https://github.com/szmarczak.png?size=100)](https://github.com/szmarczak)
---|---
[Sindre Sorhus](https://sindresorhus.com) | [Szymon Marczak](https://github.com/szmarczak)
###### Former
- [Vsevolod Strukchinsky](https://github.com/floatdrop)
- [Alexander Tesfamichael](https://github.com/alextes)
- [Brandon Smith](https://github.com/brandon93s)
- [Luke Childs](https://github.com/lukechilds)
- [Giovanni Minotti](https://github.com/Giotino)
<a name="widely-used"></a>
## These amazing companies are using Got
<table>
<tbody>
<tr>
<td align="center">
<a href="https://segment.com">
<img width="90" valign="middle" src="https://user-images.githubusercontent.com/697676/47693700-ddb62500-dbb7-11e8-8332-716a91010c2d.png">
</a>
</td>
<td align="center">
<a href="https://antora.org">
<img width="100" valign="middle" src="https://user-images.githubusercontent.com/79351/47706840-d874cc80-dbef-11e8-87c6-5f0c60cbf5dc.png">
</a>
</td>
<td align="center">
<a href="https://getvoip.com">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/10832620/47869404-429e9480-dddd-11e8-8a7a-ca43d7f06020.png">
</a>
</td>
<td align="center">
<a href="https://github.com/exoframejs/exoframe">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/365944/47791460-11a95b80-dd1a-11e8-9070-e8f2a215e03a.png">
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="http://karaokes.moe">
<img width="140" valign="middle" src="https://camo.githubusercontent.com/6860e5fa4684c14d8e1aa65df0aba4e6808ea1a9/687474703a2f2f6b6172616f6b65732e6d6f652f6173736574732f696d616765732f696e6465782e706e67">
</a>
</td>
<td align="center">
<a href="https://github.com/renovatebot/renovate">
<img width="150" valign="middle" src="https://camo.githubusercontent.com/206d470ac709b9a702a97b0c08d6f389a086793d/68747470733a2f2f72656e6f76617465626f742e636f6d2f696d616765732f6c6f676f2e737667">
</a>
</td>
<td align="center">
<a href="https://resist.bot">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/3322287/51992724-28736180-2473-11e9-9764-599cfda4b012.png">
</a>
</td>
<td align="center">
<a href="https://www.naturalcycles.com">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/170270/92244143-d0a8a200-eec2-11ea-9fc0-1c07f90b2113.png">
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://microlink.io">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/36894700/91992974-1cc5dc00-ed35-11ea-9d04-f58b42ce6a5e.png">
</a>
</td>
<td align="center">
<a href="https://radity.com">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/29518613/91814036-97fb9500-ec44-11ea-8c6c-d198cc23ca29.png">
</a>
</td>
<td align="center">
<a href="https://apify.com">
<img width="150" valign="middle" src="https://user-images.githubusercontent.com/23726914/128673143-958b5930-b677-40ef-8087-5698a0c29c45.png">
</a>
</td>
</tr>
</tbody>
</table>
<!-- <br> -->
<!-- *Creating an awesome product? Open an issue to get listed here.* -->
<br>
> Segment is a happy user of Got! Got powers the main backend API that our app talks to. It's used by our in-house RPC client that we use to communicate with all microservices.
>
> — <a href="https://github.com/vadimdemedes">Vadim Demedes</a>
> Antora, a static site generator for creating documentation sites, uses Got to download the UI bundle. In Antora, the UI bundle (aka theme) is maintained as a separate project. That project exports the UI as a zip file we call the UI bundle. The main site generator downloads that UI from a URL using Got and streams it to vinyl-zip to extract the files. Those files go on to be used to create the HTML pages and supporting assets.
>
> — <a href="https://github.com/mojavelinux">Dan Allen</a>
> GetVoIP is happily using Got in production. One of the unique capabilities of Got is the ability to handle Unix sockets which enables us to build a full control interfaces for our docker stack.
>
> — <a href="https://github.com/danielkalen">Daniel Kalen</a>
> We're using Got inside of Exoframe to handle all the communication between CLI and server. Exoframe is a self-hosted tool that allows simple one-command deployments using Docker.
>
> — <a href="https://github.com/yamalight">Tim Ermilov</a>
> Karaoke Mugen uses Got to fetch content updates from its online server.
>
> — <a href="https://github.com/AxelTerizaki">Axel Terizaki</a>
> Renovate uses Got, gh-got and gl-got to send millions of queries per day to GitHub, GitLab, npmjs, PyPi, Packagist, Docker Hub, Terraform, CircleCI, and more.
>
> — <a href="https://github.com/rarkins">Rhys Arkins</a>
> Resistbot uses Got to communicate from the API frontend where all correspondence ingresses to the officials lookup database in back.
>
> — <a href="https://github.com/chris-erickson">Chris Erickson</a>
> Natural Cycles is using Got to communicate with all kinds of 3rd-party REST APIs (over 9000!).
>
> — <a href="https://github.com/kirillgroshkov">Kirill Groshkov</a>
> Microlink is a cloud browser as an API service that uses Got widely as the main HTTP client, serving ~22M requests a month, every time a network call needs to be performed.
>
> — <a href="https://github.com/Kikobeats">Kiko Beats</a>
> Were using Got at Radity. Thanks for such an amazing work!
>
> — <a href="https://github.com/MirzayevFarid">Mirzayev Farid</a>
> Got has been a crucial component of Apify's scraping for years. We use it to extract data from billions of web pages every month, and we really appreciate the powerful API and extensibility, which allowed us to build our own specialized HTTP client on top of Got. The support has always been stellar too.
>
> — <a href="https://github.com/mnmkng">Ondra Urban</a>
## For enterprise
Available as part of the Tidelift Subscription.
The maintainers of `got` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-got?utm_source=npm-got&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)