UNPKG

nyro

Version:

A simple and effective promise-based HTTP & HTTP/2 request library that supports all HTTP methods.

1,047 lines (1,046 loc) 92.7 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var http = __importStar(require("http")); var https = __importStar(require("https")); var http2 = __importStar(require("http2-wrapper")); var zlib = __importStar(require("zlib")); var url_1 = require("url"); var utils_1 = require("./utils"); var combineUrl_1 = __importDefault(require("../helpers/combineUrl")); var errorHandler_1 = __importDefault(require("../helpers/errorHandler")); var pluginManager_1 = __importDefault(require("./pluginManager")); var http_proxy_agent_1 = require("http-proxy-agent"); var https_proxy_agent_1 = require("https-proxy-agent"); var socks_proxy_agent_1 = require("socks-proxy-agent"); var stream_1 = require("stream"); var events_1 = require("events"); var package_json_1 = __importDefault(require("../../package.json")); ; var cacheStore = new Map(); ; ; ; ; var Core = /** @class */ (function (_super) { __extends(Core, _super); function Core(baseRequestOptions) { var _this = _super.call(this) || this; _this.pluginManager = new pluginManager_1.default(); _this.baseRequestOptions = baseRequestOptions || {}; return _this; } ; Core.prototype.use = function (plugin) { return this.pluginManager.use(plugin); }; ; Core.prototype.on = function (event, listener) { return _super.prototype.on.call(this, event, listener); }; Core.prototype.once = function (event, listener) { return _super.prototype.once.call(this, event, listener); }; Core.prototype.off = function (event, listener) { return _super.prototype.off.call(this, event, listener); }; Core.prototype.emit = function (event) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return _super.prototype.emit.apply(this, __spreadArray([event], args, false)); }; /** * @param url * @returns this * @example Nyro.setURL('https://jsonplaceholder.typicode.com/posts'); * @description This function sets the URL for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setURL = function (url) { this.baseRequestOptions.url = url; return this; }; ; /** * @param baseURL * @returns this * @example Nyro.setBaseURL('https://jsonplaceholder.typicode.com'); * @description This function sets the base URL for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setBaseURL = function (baseURL) { this.baseRequestOptions.baseURL = baseURL; return this; }; ; /** * @param path * @returns this * @example Nyro.setPath('/posts'); * @description This function sets the path for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setPath = function (path) { this.baseRequestOptions.path = path; return this; }; ; /** * @param bodySchema * @returns this * @example Nyro.setBodySchema({ title: String, body: String }); * @description This function sets the body schema for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setBodySchema = function (bodySchema) { this.baseRequestOptions.bodySchema = bodySchema; return this; }; ; /** * @param auth * @returns this * @example Nyro.setAuth({ username: 'user', password: 'pass' }); * @description This function sets the authentication credentials for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setAuth = function (auth) { this.baseRequestOptions.auth = auth; return this; }; ; /** * @param proxy * @returns this * @example Nyro.setProxy({ host: 'localhost', port: 8080, protocol: 'http' }); * @description This function sets the proxy for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setProxy = function (proxy) { this.baseRequestOptions.proxy = proxy; return this; }; ; /** * @param method * @returns this * @example Nyro.setMethod('GET'); * @description This function sets the method for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMethod = function (method) { this.baseRequestOptions.method = method; return this; }; ; /** * @param headers * @returns this * @example Nyro.setHeaders({ 'Content-Type': 'application/json' }); * @description This function sets the headers for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setHeaders = function (headers) { this.baseRequestOptions.headers = headers; return this; }; ; /** * @param params * @returns this * @example Nyro.setParams({ id: '1' }); * @description This function sets the query parameters for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setParams = function (params) { this.baseRequestOptions.params = params; return this; }; ; /** * @param query * @returns this * @example Nyro.setQuery({ id: '1' }); * @description This function sets the query parameters for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setQuery = function (query) { this.baseRequestOptions.query = query; return this; }; ; /** * @param body * @returns this * @example Nyro.setBody({ title: 'foo', body: 'bar', userId: 1 }); * @description This function sets the body for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setBody = function (body) { this.baseRequestOptions.body = body; return this; }; ; /** * @param timeout * @returns this * @example Nyro.setTimeout(5000); * @description This function sets the timeout for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setTimeout = function (timeout) { this.baseRequestOptions.timeout = timeout; return this; }; ; /** * @param retryOn * @returns this * @example Nyro.setRetryOn((req, error) => error.code === 'ETIMEDOUT'); * @description This function sets the retry condition for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setRetryOn = function (retryOn) { this.baseRequestOptions.onRetry = retryOn; return this; }; ; /** * @param retries * @returns this * @example Nyro.setRetries(3); * @description This function sets the number of retries for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setRetries = function (retries) { this.baseRequestOptions.retries = retries; return this; }; ; /** * @param validateStatus * @returns this * @example Nyro.setValidateStatus((status) => status >= 200 && status < 300); * @description This function sets the status validation for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setValidateStatus = function (validateStatus) { this.baseRequestOptions.validateStatus = validateStatus; return this; }; ; /** * @param maxBodyLength * @returns this * @example Nyro.setMaxBodyLength(1000); * @description This function sets the maximum body length for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxBodyLength = function (maxBodyLength) { this.baseRequestOptions.maxBodyLength = maxBodyLength; return this; }; ; /** * @param maxContentLength * @returns this * @example Nyro.setMaxContentLength(1000); * @description This function sets the maximum content length for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxContentLength = function (maxContentLength) { this.baseRequestOptions.maxContentLength = maxContentLength; return this; }; ; /** * @param maxRate * @returns this * @example Nyro.setMaxRate(1000); * @description This function sets the maximum rate for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxRate = function (maxRate) { this.baseRequestOptions.maxRate = maxRate; return this; }; ; /** * @param signal * @returns this * @example Nyro.setSignal(signal); * @description This function sets the signal for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setSignal = function (signal) { this.baseRequestOptions.signal = signal; return this; }; ; /** * @param onDownloadProgress * @returns this * @example Nyro.setOnDownloadProgress((progress) => console.log(progress)); * @description This function sets the download progress for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setOnDownloadProgress = function (onDownloadProgress) { this.baseRequestOptions.onDownloadProgress = onDownloadProgress; return this; }; ; /** * @param timeoutErrorMessage * @returns this * @example Nyro.setTimeoutErrorMessage('Request timed out'); * @description This function sets the timeout error message for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setTimeoutErrorMessage = function (timeoutErrorMessage) { this.baseRequestOptions.timeoutErrorMessage = timeoutErrorMessage; return this; }; ; /** * @param responseType * @returns this * @example Nyro.setResponseType('json'); * @description This function sets the response type for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setResponseType = function (responseType) { this.baseRequestOptions.responseType = responseType; return this; }; ; /** * @param responseEncoding * @returns this * @example Nyro.setResponseEncoding('utf8'); * @description This function sets the response encoding for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setResponseEncoding = function (responseEncoding) { this.baseRequestOptions.responseEncoding = responseEncoding; return this; }; ; /** * @param maxRedirects * @returns this * @example Nyro.setMaxRedirects(3); * @description This function sets the maximum number of redirects for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setMaxRedirects = function (maxRedirects) { this.baseRequestOptions.maxRedirects = maxRedirects; return this; }; ; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setRetryDelay = function (retryDelay) { this.baseRequestOptions.retryDelay = retryDelay; return this; }; ; /** * @param decompress * @returns this * @example Nyro.setDecompress(true); * @description This function sets the decompress option for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ Core.prototype.setDecompress = function (decompress) { this.baseRequestOptions.decompress = decompress; return this; }; ; /*-------------------------------------------------------*/ /*----------------LINE-------------BREAK-----------------*/ /*-------------------------------------------------------*/ /** * Sends a GET request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.get('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a GET request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET|MDN web docs} */ Core.prototype.get = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'GET'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a POST request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.post('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a POST request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST|MDN web docs} */ Core.prototype.post = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'POST'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a PUT request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.put('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a PUT request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT|MDN web docs} */ Core.prototype.put = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'PUT'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a DELETE request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.delete('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a DELETE request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE|MDN web docs} */ Core.prototype.delete = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'DELETE'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a PATCH request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.patch('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a PATCH request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH|MDN web docs} */ Core.prototype.patch = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'PATCH'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a HEAD request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.head('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a HEAD request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD|MDN web docs} */ Core.prototype.head = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'HEAD'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends an OPTIONS request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.options('https://jsonplaceholder.typicode.com/posts'); * @description This function sends an OPTIONS request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS|MDN web docs} */ Core.prototype.options = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'OPTIONS'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a CONNECT request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.connect('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a CONNECT request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT|MDN web docs} */ Core.prototype.connect = function (url, options) { return __awaiter(this, void 0, void 0, function () { var method; return __generator(this, function (_a) { method = 'CONNECT'; if (this.baseRequestOptions && this.baseRequestOptions.method !== method) this.baseRequestOptions.method = method; return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: this.baseRequestOptions.method || method, url: url }))]; }); }); }; ; /** * Sends a TRACE request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.trace('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a TRACE request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE|MDN web docs} */ Core.prototype.trace = function (url, options) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.request(!url ? this.baseRequestOptions : __assign(__assign({}, options), { method: 'TRACE', url: url }))]; }); }); }; ; /** * Downloads a file from the specified URL. * @param url - The URL to download the file from. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.download('https://jsonplaceholder.typicode.com/posts'); * @description This function downloads a file from the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type|MDN web docs} */ Core.prototype.download = function (url, options) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.request(__assign(__assign({}, options), { responseType: 'stream', isStream: true, method: 'GET', url: url }))]; }); }); }; ; /** * Sends a request to the specified URL with pagination. * @param options - The request options. * @param paginationOptions - The pagination options. * @returns A promise that resolves with an array of HTTP responses. * @example Nyro.pagination({ url: 'https://jsonplaceholder.typicode.com/posts', method: 'GET' }, { pageParam: 'page', limitParam: 'limit', maxPages: 3 }); * @description This function sends a request to the specified URL with pagination and returns a promise that resolves with an array of HTTP responses. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link|MDN web docs} */ Core.prototype.pagination = function (options, paginationOptions) { return __awaiter(this, void 0, void 0, function () { var results, page, hasMore, paginatedOptions, response; var _a; var _b, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: results = []; page = 1; hasMore = true; _d.label = 1; case 1: if (!hasMore) return [3 /*break*/, 3]; paginatedOptions = __assign(__assign({}, options), { params: __assign(__assign({}, options === null || options === void 0 ? void 0 : options.params), (_a = {}, _a[(paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.pageParam) || 'page'] = page, _a)) }); return [4 /*yield*/, this.request(paginatedOptions)]; case 2: response = _d.sent(); if (Array.isArray(response)) { results.push.apply(results, response); } else { results.push(response); } hasMore = Array.isArray(response) && response.length > 0 && (!((_b = paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.maxPages) !== null && _b !== void 0 ? _b : 0) || page < ((_c = paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.maxPages) !== null && _c !== void 0 ? _c : 0)); page++; return [3 /*break*/, 1]; case 3: return [2 /*return*/, results]; } }); }); }; ; /** * Sends multiple requests to the specified URLs. * @param requests - The request options. * @returns A promise that resolves with an array of HTTP responses. * @example Nyro.queue([ * { url: 'https://jsonplaceholder.typicode.com/posts/1', method: 'GET' }, * { url: 'https://jsonplaceholder.typicode.com/posts/2', method: 'POST' } * ]); * @description This function sends multiple requests to the specified URLs and returns a promise that resolves with an array of HTTP responses. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} */ Core.prototype.queue = function (requests, queueOptions) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, Promise.all(requests.map(function (request, index) { return new Promise(function (resolve) { var _a; return setTimeout(function () { return resolve(_this.request(request)); }, index * ((_a = queueOptions === null || queueOptions === void 0 ? void 0 : queueOptions.delay) !== null && _a !== void 0 ? _a : 0)); }); }))]; }); }); }; ; /** * Extends the default request options with the provided options. * * @param extendOptions - The options to extend the default request options with. * @returns An object with the execute function to make the request and the options used for the request. * @example Nyro.extend({ * url: 'https://jsonplaceholder.typicode.com/posts', * method: 'GET', * headers: { * 'Content-Type': 'application/json' * } * }); * @description This function allows you to create a new request with the provided options, while keeping the default options for future requests. */ Core.prototype.extend = function (extendOptions) { return __awaiter(this, void 0, void 0, function () { var options; return __generator(this, function (_a) { options = __assign(__assign({}, this.baseRequestOptions), extendOptions); return [2 /*return*/, new Core(options)]; }); }); }; ; /** * Creates a new instance of the Nyro library with the provided options. * * @param options - The request options. * @returns A new instance of the Nyro library with the provided options. * @example Nyro.create({ * url: 'https://jsonplaceholder.typicode.com/posts', * method: 'GET', * headers: { * 'Content-Type': 'application/json' * } * }); * @description This function creates a new instance of the Nyro library with the provided options. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} */ Core.prototype.create = function (options) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new Core(options)]; }); }); }; /** * Core function for handling HTTP requests. * * @param options - The request options. * @param currentRedirects - The number of redirects that have occurred. * @returns A promise that resolves with the HTTP response. */ Core.prototype.request = function (options_1) { return __awaiter(this, arguments, void 0, function (options, currentRedirects, attempt, visitedUrls) { var combinedURL, fullUrl, params, query, key, isHttps, _a, username, password, token, onRequest, validateStatus, onResponse, onTimeout, onRedirect, onChunk, onRequestOptions, requestOptions, proxyAuth, proxyUrl, protocol, dataString, startTimestamp, lib; var _this = this; var _b, _c, _d, _e, _f, _g, _h, _j, _k; if (currentRedirects === void 0) { currentRedirects = 0; } if (attempt === void 0) { attempt = 1; } if (visitedUrls === void 0) { visitedUrls = new Set(); } return __generator(this, function (_l) { if (!options) { options = __assign({}, this.baseRequestOptions); } else { options = __assign(__assign({}, this.baseRequestOptions), options); } ; combinedURL = (0, combineUrl_1.default)((options === null || options === void 0 ? void 0 : options.baseURL) || '', (options === null || options === void 0 ? void 0 : options.url) || "", (options === null || options === void 0 ? void 0 : options.path) || ''); try { fullUrl = new url_1.URL(combinedURL); } catch (error) { /* this.emit('error', ({ statusCode: 400, message: `Invalid URL: ${combinedURL}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid URL: ".concat(combinedURL), name: 'Request', requestOptions: options, }))]; } visitedUrls.add(fullUrl.toString()); if ((_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.aborted) { /* this.emit('error',({ statusCode: 0, message: 'Request aborted', name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 0, message: 'Request aborted', name: 'Request', requestOptions: options, }))]; } ; if (options === null || options === void 0 ? void 0 : options.port) { options.port = (options === null || options === void 0 ? void 0 : options.port) || (fullUrl.protocol === 'https:' ? 443 : 80); } ; if (options === null || options === void 0 ? void 0 : options.path) { fullUrl.pathname += options.path; } if (options === null || options === void 0 ? void 0 : options.isStream) { options.responseType = 'stream'; } if (options === null || options === void 0 ? void 0 : options.params) { params = new url_1.URLSearchParams(options.params); fullUrl.search = params.toString(); } if (['json', 'text', 'blob', 'stream', 'arrayBuffer', 'document'].indexOf((options === null || options === void 0 ? void 0 : options.responseType) || 'json') === -1) { /* this.emit('error',({ statusCode: 400, message: `Invalid response type: ${options?.responseType}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid response type: ".concat(options === null || options === void 0 ? void 0 : options.responseType), name: 'Request', requestOptions: options, }))]; } ; options.method = ((_c = options.method) === null || _c === void 0 ? void 0 : _c.toUpperCase()) || 'GET'; if (options && options.method && ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'CONNECT', 'TRACE'].indexOf(options.method) === -1) { /* this.emit('error', ({ statusCode: 400, message: `Invalid request method: ${options.method}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid request method: ".concat(options.method), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.timeout) && options.timeout < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid timeout: ${options.timeout}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid timeout: ".concat(options.timeout), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxRedirects) && options.maxRedirects < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid number of redirects: ${options.maxRedirects}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid number of redirects: ".concat(options.maxRedirects), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxBodyLength) && options.maxBodyLength < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid max body length: ${options.maxBodyLength}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid max body length: ".concat(options.maxBodyLength), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxContentLength) && options.maxContentLength < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid max content length: ${options.maxContentLength}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid max content length: ".concat(options.maxContentLength), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.maxRate) && options.maxRate < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid max rate: ${options.maxRate}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid max rate: ".concat(options.maxRate), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.retryDelay) && options.retryDelay < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid retry delay: ${options.retryDelay}`, name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid retry delay: ".concat(options.retryDelay), name: 'Request', requestOptions: options, }))]; } ; if ((options === null || options === void 0 ? void 0 : options.retries) && options.retries < 0) { /* this.emit('error', ({ statusCode: 400, message: `Invalid number of retries: ${options.retries}`, name: 'Request', requestOptions: options })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: "Invalid number of retries: ".concat(options.retries), name: 'Request', requestOptions: options }))]; } ; if (options === null || options === void 0 ? void 0 : options.query) { query = new url_1.URLSearchParams(); for (key in options.query) { if (Object.prototype.hasOwnProperty.call(options.query, key)) { query.append(key, String(options.query[key])); } } fullUrl.search += (fullUrl.search ? '&' : '') + query.toString(); } if (options.useHttp2 == undefined) options.useHttp2 = true; if (options.useHttp2 && !http2) { /* this.emit('error', ({ statusCode: 400, message: 'http2 is not available in this environment', name: 'Request', requestOptions: options, })); */ return [2 /*return*/, Promise.reject(new errorHandler_1.default({ statusCode: 400, message: 'http2 is not available in this environment', name: 'Request', requestOptions: options, }))]; } isHttps = fullUrl.protocol === 'https:'; if (!isHttps && ((_d = options.sslOptions) === null || _d === void 0 ? void 0 : _d.passphrase) || ((_e = options.sslOptions) === null || _e === void 0 ? void 0 : _e.ca) || ((_f = options.sslOptions) === null || _f === void 0 ? void 0 : _f.cert) || ((_g = options.sslOptions) === null || _g === void 0 ? void 0 : _g.key) || ((_h = options.sslOptions) === null || _h === void 0 ? void 0 : _h.rejectUnauthorized) || ((_j = options.sslOptions) === null || _j === void 0 ? void 0 : _j.secureProtocol)) { /* this.emit('error', ({