diff --git a/dist/main/index.js b/dist/main/index.js index e936948..c7c2648 100644 --- a/dist/main/index.js +++ b/dist/main/index.js @@ -108,7 +108,7 @@ module.exports = Octokit; const os = __webpack_require__(87); const macosRelease = __webpack_require__(118); -const winRelease = __webpack_require__(49); +const winRelease = __webpack_require__(494); const osName = (platform, release) => { if (!platform && release) { @@ -153,12 +153,58 @@ const osName = (platform, release) => { module.exports = osName; +/***/ }), + +/***/ 3: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} + +function isPlainObject(o) { + var ctor,prot; + + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +} + +exports.isPlainObject = isPlainObject; + + /***/ }), /***/ 9: /***/ (function(module, __unusedexports, __webpack_require__) { -var once = __webpack_require__(969); +var once = __webpack_require__(49); var noop = function() {}; @@ -276,7 +322,7 @@ exports.default = (url) => { href: url.href, path: `${url.pathname || ''}${url.search || ''}` }; - if (is_1.default.string(url.port) && url.port.length !== 0) { + if (is_1.default.string(url.port) && url.port.length > 0) { options.port = Number(url.port); } if (url.username || url.password) { @@ -349,7 +395,7 @@ module.exports = eval("require")("encoding"); module.exports = authenticationPlugin; const { Deprecation } = __webpack_require__(692); -const once = __webpack_require__(969); +const once = __webpack_require__(49); const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation)); @@ -450,6 +496,12 @@ const DEFAULT_COMMIT_TYPES = [ "wip", ]; const isValidCommitMessage = (message, availableTypes = DEFAULT_COMMIT_TYPES) => { + // Exceptions. + // This is a message that's auto-generated by git. Can't do much about it unfortunately. Let's allow it. + if (message.startsWith('Merge ')) { + return true; + } + // Commit message doesn't fall into the exceptions group. Let's do the validation. let [possiblyValidCommitType] = message.split(":"); possiblyValidCommitType = possiblyValidCommitType.toLowerCase(); // Let's remove scope if present. @@ -464,6 +516,14 @@ const isValidCommitMessage = (message, availableTypes = DEFAULT_COMMIT_TYPES) => }; /* harmony default export */ var isValidCommitMesage = (isValidCommitMessage); +// EXTERNAL MODULE: ./node_modules/lodash.get/index.js +var lodash_get = __webpack_require__(854); +var lodash_get_default = /*#__PURE__*/__webpack_require__.n(lodash_get); + +// EXTERNAL MODULE: ./node_modules/got/dist/source/index.js +var source = __webpack_require__(77); +var source_default = /*#__PURE__*/__webpack_require__.n(source); + // CONCATENATED MODULE: ./src/extractCommits.ts var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { @@ -473,19 +533,19 @@ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _argume step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -const get = __webpack_require__(854); -const got = __webpack_require__(77); + + const extractCommits = (context) => __awaiter(undefined, void 0, void 0, function* () { // For "push" events, commits can be found in the "context.payload.commits". - const pushCommits = Array.isArray(get(context, "payload.commits")); + const pushCommits = Array.isArray(lodash_get_default()(context, "payload.commits")); if (pushCommits) { return context.payload.commits; } // For PRs, we need to get a list of commits via the GH API: - const prCommitsUrl = get(context, "payload.pull_request.commits_url"); + const prCommitsUrl = lodash_get_default()(context, "payload.pull_request.commits_url"); if (prCommitsUrl) { try { - const { body } = yield got.get(prCommitsUrl, { + const { body } = yield source_default().get(prCommitsUrl, { responseType: "json", }); if (Array.isArray(body)) { @@ -510,14 +570,14 @@ var main_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arg step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -const { context } = __webpack_require__(469); -const core = __webpack_require__(470); +const { context: main_context } = __webpack_require__(469); +const core = __webpack_require__(393); function run() { return main_awaiter(this, void 0, void 0, function* () { core.info(`ℹ️ Checking if commit messages are following the Conventional Commits specification...`); - const extractedCommits = yield src_extractCommits(context); + const extractedCommits = yield src_extractCommits(main_context); if (extractedCommits.length === 0) { core.info(`No commits to check, skipping...`); return; @@ -553,32 +613,45 @@ run(); "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; Object.defineProperty(exports, "__esModule", { value: true }); -const p_cancelable_1 = __webpack_require__(557); -exports.CancelError = p_cancelable_1.CancelError; +exports.CancelError = exports.ParseError = void 0; const core_1 = __webpack_require__(946); -exports.RequestError = -// Errors to be exported -core_1.RequestError; -exports.MaxRedirectsError = core_1.MaxRedirectsError; -exports.CacheError = core_1.CacheError; -exports.UploadError = core_1.UploadError; -exports.TimeoutError = core_1.TimeoutError; -exports.HTTPError = core_1.HTTPError; -exports.ReadError = core_1.ReadError; -exports.UnsupportedProtocolError = core_1.UnsupportedProtocolError; +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ class ParseError extends core_1.RequestError { constructor(error, response) { const { options } = response.request; super(`${error.message} in "${options.url.toString()}"`, error, response.request); this.name = 'ParseError'; - Object.defineProperty(this, 'response', { - enumerable: false, - value: response - }); } } exports.ParseError = ParseError; +/** +An error to be thrown when the request is aborted with `.cancel()`. +*/ +class CancelError extends core_1.RequestError { + constructor(request) { + super('Promise was canceled', {}, request); + this.name = 'CancelError'; + } + get isCanceled() { + return true; + } +} +exports.CancelError = CancelError; +__exportStar(__webpack_require__(946), exports); /***/ }), @@ -661,59 +734,48 @@ exports.default = WeakableMap; /***/ 49: /***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +var wrappy = __webpack_require__(11) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -const os = __webpack_require__(87); -const execa = __webpack_require__(955); +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -// Reference: https://www.gaijin.at/en/lstwinver.php -const names = new Map([ - ['10.0', '10'], - ['6.3', '8.1'], - ['6.2', '8'], - ['6.1', '7'], - ['6.0', 'Vista'], - ['5.2', 'Server 2003'], - ['5.1', 'XP'], - ['5.0', '2000'], - ['4.9', 'ME'], - ['4.1', '98'], - ['4.0', '95'] -]); + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) -const windowsRelease = release => { - const version = /\d+\.\d/.exec(release || os.release()); +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} - if (release && !version) { - throw new Error('`release` argument doesn\'t match `n.n`'); - } - - const ver = (version || [])[0]; - - // Server 2008, 2012, 2016, and 2019 versions are ambiguous with desktop versions and must be detected at runtime. - // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version - // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx - // If `wmic` is obsoloete (later versions of Windows 10), use PowerShell instead. - // If the resulting caption contains the year 2008, 2012, 2016 or 2019, it is a server version, so return a server OS name. - if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) { - let stdout; - try { - stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; - } catch (_) { - stdout = execa.sync('powershell', ['(Get-CimInstance -ClassName Win32_OperatingSystem).caption']).stdout || ''; - } - - const year = (stdout.match(/2008|2012|2016|2019/) || [])[0]; - - if (year) { - return `Server ${year}`; - } - } - - return names.get(ver); -}; - -module.exports = windowsRelease; +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} /***/ }), @@ -952,9 +1014,16 @@ module.exports.default = normalizeUrl; "use strict"; -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; Object.defineProperty(exports, "__esModule", { value: true }); const url_1 = __webpack_require__(835); const create_1 = __webpack_require__(903); @@ -1057,11 +1126,13 @@ const defaults = { filter: () => true, shouldContinue: () => true, countLimit: Infinity, + backoff: 0, requestLimit: 10000, stackAllItems: true }, parseJson: (text) => JSON.parse(text), - stringifyJson: (object) => JSON.stringify(object) + stringifyJson: (object) => JSON.stringify(object), + cacheOptions: {} }, handlers: [create_1.defaultHandler], mutableDefaults: false @@ -1071,8 +1142,9 @@ exports.default = got; // For CommonJS default export support module.exports = got; module.exports.default = got; -__export(__webpack_require__(903)); -__export(__webpack_require__(952)); +module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267 +__exportStar(__webpack_require__(903), exports); +__exportStar(__webpack_require__(952), exports); /***/ }), @@ -1133,6 +1205,32 @@ module.exports.array = (stream, options) => getStream(stream, Object.assign({}, module.exports.MaxBufferError = MaxBufferError; +/***/ }), + +/***/ 82: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +//# sourceMappingURL=utils.js.map + /***/ }), /***/ 87: @@ -1267,6 +1365,42 @@ class Response extends Readable { module.exports = Response; +/***/ }), + +/***/ 102: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +// For internal use, subject to change. +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__webpack_require__(747)); +const os = __importStar(__webpack_require__(87)); +const utils_1 = __webpack_require__(82); +function issueCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); + } + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueCommand = issueCommand; +//# sourceMappingURL=file-command.js.map + /***/ }), /***/ 118: @@ -1277,28 +1411,32 @@ module.exports = Response; const os = __webpack_require__(87); const nameMap = new Map([ - [19, 'Catalina'], - [18, 'Mojave'], - [17, 'High Sierra'], - [16, 'Sierra'], - [15, 'El Capitan'], - [14, 'Yosemite'], - [13, 'Mavericks'], - [12, 'Mountain Lion'], - [11, 'Lion'], - [10, 'Snow Leopard'], - [9, 'Leopard'], - [8, 'Tiger'], - [7, 'Panther'], - [6, 'Jaguar'], - [5, 'Puma'] + [20, ['Big Sur', '11']], + [19, ['Catalina', '10.15']], + [18, ['Mojave', '10.14']], + [17, ['High Sierra', '10.13']], + [16, ['Sierra', '10.12']], + [15, ['El Capitan', '10.11']], + [14, ['Yosemite', '10.10']], + [13, ['Mavericks', '10.9']], + [12, ['Mountain Lion', '10.8']], + [11, ['Lion', '10.7']], + [10, ['Snow Leopard', '10.6']], + [9, ['Leopard', '10.5']], + [8, ['Tiger', '10.4']], + [7, ['Panther', '10.3']], + [6, ['Jaguar', '10.2']], + [5, ['Puma', '10.1']] ]); const macosRelease = release => { release = Number((release || os.release()).split('.')[0]); + + const [name, version] = nameMap.get(release); + return { - name: nameMap.get(release), - version: '10.' + (release - 4) + name, + version }; }; @@ -1307,6 +1445,39 @@ module.exports = macosRelease; module.exports.default = macosRelease; +/***/ }), + +/***/ 121: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = __webpack_require__(36); +const parseBody = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); + } + if (responseType === 'buffer') { + return rawBody; + } + throw new types_1.ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error' + }, response); + } + catch (error) { + throw new types_1.ParseError(error, response); + } +}; +exports.default = parseBody; + + /***/ }), /***/ 126: @@ -2526,6 +2697,7 @@ function withAuthorizationPrefix(authorization) { "use strict"; +const {constants: BufferConstants} = __webpack_require__(407); const pump = __webpack_require__(453); const bufferStream = __webpack_require__(966); @@ -2551,7 +2723,8 @@ async function getStream(inputStream, options) { let stream; await new Promise((resolve, reject) => { const rejectPromise = error => { - if (error) { // A null check + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } @@ -3298,6 +3471,7 @@ const request = (url, options, callback) => { }; const get = (url, options, callback) => { + // eslint-disable-next-line unicorn/prevent-abbreviations const req = new ClientRequest(url, options, callback); req.end(); @@ -3401,7 +3575,7 @@ const kOptions = Symbol('options'); const kFlushedHeaders = Symbol('flushedHeaders'); const kJobs = Symbol('jobs'); -const isValidHttpToken = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/; +const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; class ClientRequest extends Writable { @@ -3442,16 +3616,18 @@ class ClientRequest extends Writable { throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent); } - if (!options.port) { - options.port = options.defaultPort || (this.agent && this.agent.defaultPort) || 443; - } - - options.host = options.hostname || options.host || 'localhost'; - if (options.protocol && options.protocol !== 'https:') { throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:'); } + const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443; + const host = options.hostname || options.host || 'localhost'; + + // Don't enforce the origin via options. It may be changed in an Agent. + delete options.hostname; + delete options.host; + delete options.port; + const {timeout} = options; options.timeout = undefined; @@ -3461,7 +3637,7 @@ class ClientRequest extends Writable { this.socket = null; this.connection = null; - this.method = options.method; + this.method = options.method || 'GET'; this.path = options.path; this.res = null; @@ -3484,23 +3660,20 @@ class ClientRequest extends Writable { this[kOptions] = options; // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. - // What about IPv6? Square brackets? - if (options.port === 443) { - options.origin = `https://${options.host}`; + if (port === 443) { + this[kOrigin] = `https://${host}`; if (!(':authority' in this[kHeaders])) { - this[kHeaders][':authority'] = options.host; + this[kHeaders][':authority'] = host; } } else { - options.origin = `https://${options.host}:${options.port}`; + this[kOrigin] = `https://${host}:${port}`; if (!(':authority' in this[kHeaders])) { - this[kHeaders][':authority'] = `${options.host}:${options.port}`; + this[kHeaders][':authority'] = `${host}:${port}`; } } - this[kOrigin] = options; - if (timeout) { this.setTimeout(timeout); } @@ -3532,7 +3705,18 @@ class ClientRequest extends Writable { } } + get _mustNotHaveABody() { + return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; + } + _write(chunk, encoding, callback) { + // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 + if (this._mustNotHaveABody) { + callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); + /* istanbul ignore next: Node.js 12 throws directly */ + return; + } + this.flushHeaders(); const callWrite = () => this._request.write(chunk, encoding, callback); @@ -3550,7 +3734,16 @@ class ClientRequest extends Writable { this.flushHeaders(); - const callEnd = () => this._request.end(callback); + const callEnd = () => { + // For GET, HEAD and DELETE + if (this._mustNotHaveABody) { + callback(); + return; + } + + this._request.end(callback); + }; + if (this._request) { callEnd(); } else { @@ -3607,8 +3800,22 @@ class ClientRequest extends Writable { proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']); } + // Wait for the `finish` event. We don't want to emit the `response` event + // before `request.end()` is called. + const waitForEnd = fn => { + return (...args) => { + if (!this.writable && !this.destroyed) { + fn(...args); + } else { + this.once('finish', () => { + fn(...args); + }); + } + }; + }; + // This event tells we are ready to listen for the data. - stream.once('response', (headers, flags, rawHeaders) => { + stream.once('response', waitForEnd((headers, flags, rawHeaders) => { // If we were to emit raw request stream, it would be as fast as the native approach. // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); @@ -3660,18 +3867,20 @@ class ClientRequest extends Writable { response._dump(); } } - }); + })); // Emits `information` event - stream.once('headers', headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})); + stream.once('headers', waitForEnd( + headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]}) + )); - stream.once('trailers', (trailers, flags, rawTrailers) => { + stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => { const {res} = this; // Assigns trailers to the response object. res.trailers = trailers; res.rawTrailers = rawTrailers; - }); + })); const {socket} = stream.session; this.socket = socket; @@ -3687,9 +3896,7 @@ class ClientRequest extends Writable { // Makes a HTTP2 request if (this[kSession]) { try { - onStream(this[kSession].request(this[kHeaders], { - endStream: false - })); + onStream(this[kSession].request(this[kHeaders])); } catch (error) { this.emit('error', error); } @@ -3798,7 +4005,7 @@ exports.default = (message) => { return; } alreadyWarned.add(message); - // @ts-ignore Missing types. + // @ts-expect-error Missing types. process.emitWarning(`Got: ${message}`, { type: 'DeprecationWarning' }); @@ -3814,7 +4021,7 @@ module.exports = authenticationPlugin; const { createTokenAuth } = __webpack_require__(813); const { Deprecation } = __webpack_require__(692); -const once = __webpack_require__(969); +const once = __webpack_require__(49); const beforeRequest = __webpack_require__(863); const requestError = __webpack_require__(293); @@ -4053,7 +4260,7 @@ module.exports = require("https"); /***/ 215: /***/ (function(module) { -module.exports = {"name":"@octokit/rest","version":"16.43.1","publishConfig":{"access":"public"},"description":"GitHub REST API client for Node.js","keywords":["octokit","github","rest","api-client"],"author":"Gregor Martynus (https://github.com/gr2m)","contributors":[{"name":"Mike de Boer","email":"info@mikedeboer.nl"},{"name":"Fabian Jakobs","email":"fabian@c9.io"},{"name":"Joe Gallo","email":"joe@brassafrax.com"},{"name":"Gregor Martynus","url":"https://github.com/gr2m"}],"repository":"https://github.com/octokit/rest.js","dependencies":{"@octokit/auth-token":"^2.4.0","@octokit/plugin-paginate-rest":"^1.1.1","@octokit/plugin-request-log":"^1.0.0","@octokit/plugin-rest-endpoint-methods":"2.4.0","@octokit/request":"^5.2.0","@octokit/request-error":"^1.0.2","atob-lite":"^2.0.0","before-after-hook":"^2.0.0","btoa-lite":"^1.0.0","deprecation":"^2.0.0","lodash.get":"^4.4.2","lodash.set":"^4.3.2","lodash.uniq":"^4.5.0","octokit-pagination-methods":"^1.1.0","once":"^1.4.0","universal-user-agent":"^4.0.0"},"devDependencies":{"@gimenete/type-writer":"^0.1.3","@octokit/auth":"^1.1.1","@octokit/fixtures-server":"^5.0.6","@octokit/graphql":"^4.2.0","@types/node":"^13.1.0","bundlesize":"^0.18.0","chai":"^4.1.2","compression-webpack-plugin":"^3.1.0","cypress":"^3.0.0","glob":"^7.1.2","http-proxy-agent":"^4.0.0","lodash.camelcase":"^4.3.0","lodash.merge":"^4.6.1","lodash.upperfirst":"^4.3.1","lolex":"^5.1.2","mkdirp":"^1.0.0","mocha":"^7.0.1","mustache":"^4.0.0","nock":"^11.3.3","npm-run-all":"^4.1.2","nyc":"^15.0.0","prettier":"^1.14.2","proxy":"^1.0.0","semantic-release":"^17.0.0","sinon":"^8.0.0","sinon-chai":"^3.0.0","sort-keys":"^4.0.0","string-to-arraybuffer":"^1.0.0","string-to-jsdoc-comment":"^1.0.0","typescript":"^3.3.1","webpack":"^4.0.0","webpack-bundle-analyzer":"^3.0.0","webpack-cli":"^3.0.0"},"types":"index.d.ts","scripts":{"coverage":"nyc report --reporter=html && open coverage/index.html","lint":"prettier --check '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","lint:fix":"prettier --write '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","pretest":"npm run -s lint","test":"nyc mocha test/mocha-node-setup.js \"test/*/**/*-test.js\"","test:browser":"cypress run --browser chrome","build":"npm-run-all build:*","build:ts":"npm run -s update-endpoints:typescript","prebuild:browser":"mkdirp dist/","build:browser":"npm-run-all build:browser:*","build:browser:development":"webpack --mode development --entry . --output-library=Octokit --output=./dist/octokit-rest.js --profile --json > dist/bundle-stats.json","build:browser:production":"webpack --mode production --entry . --plugin=compression-webpack-plugin --output-library=Octokit --output-path=./dist --output-filename=octokit-rest.min.js --devtool source-map","generate-bundle-report":"webpack-bundle-analyzer dist/bundle-stats.json --mode=static --no-open --report dist/bundle-report.html","update-endpoints":"npm-run-all update-endpoints:*","update-endpoints:fetch-json":"node scripts/update-endpoints/fetch-json","update-endpoints:typescript":"node scripts/update-endpoints/typescript","prevalidate:ts":"npm run -s build:ts","validate:ts":"tsc --target es6 --noImplicitAny index.d.ts","postvalidate:ts":"tsc --noEmit --target es6 test/typescript-validate.ts","start-fixtures-server":"octokit-fixtures-server"},"license":"MIT","files":["index.js","index.d.ts","lib","plugins"],"nyc":{"ignore":["test"]},"release":{"publish":["@semantic-release/npm",{"path":"@semantic-release/github","assets":["dist/*","!dist/*.map.gz"]}]},"bundlesize":[{"path":"./dist/octokit-rest.min.js.gz","maxSize":"33 kB"}]}; +module.exports = {"name":"@octokit/rest","version":"16.43.2","publishConfig":{"access":"public"},"description":"GitHub REST API client for Node.js","keywords":["octokit","github","rest","api-client"],"author":"Gregor Martynus (https://github.com/gr2m)","contributors":[{"name":"Mike de Boer","email":"info@mikedeboer.nl"},{"name":"Fabian Jakobs","email":"fabian@c9.io"},{"name":"Joe Gallo","email":"joe@brassafrax.com"},{"name":"Gregor Martynus","url":"https://github.com/gr2m"}],"repository":"https://github.com/octokit/rest.js","dependencies":{"@octokit/auth-token":"^2.4.0","@octokit/plugin-paginate-rest":"^1.1.1","@octokit/plugin-request-log":"^1.0.0","@octokit/plugin-rest-endpoint-methods":"2.4.0","@octokit/request":"^5.2.0","@octokit/request-error":"^1.0.2","atob-lite":"^2.0.0","before-after-hook":"^2.0.0","btoa-lite":"^1.0.0","deprecation":"^2.0.0","lodash.get":"^4.4.2","lodash.set":"^4.3.2","lodash.uniq":"^4.5.0","octokit-pagination-methods":"^1.1.0","once":"^1.4.0","universal-user-agent":"^4.0.0"},"devDependencies":{"@gimenete/type-writer":"^0.1.3","@octokit/auth":"^1.1.1","@octokit/fixtures-server":"^5.0.6","@octokit/graphql":"^4.2.0","@types/node":"^13.1.0","bundlesize":"^0.18.0","chai":"^4.1.2","compression-webpack-plugin":"^3.1.0","cypress":"^4.0.0","glob":"^7.1.2","http-proxy-agent":"^4.0.0","lodash.camelcase":"^4.3.0","lodash.merge":"^4.6.1","lodash.upperfirst":"^4.3.1","lolex":"^6.0.0","mkdirp":"^1.0.0","mocha":"^7.0.1","mustache":"^4.0.0","nock":"^11.3.3","npm-run-all":"^4.1.2","nyc":"^15.0.0","prettier":"^1.14.2","proxy":"^1.0.0","semantic-release":"^17.0.0","sinon":"^8.0.0","sinon-chai":"^3.0.0","sort-keys":"^4.0.0","string-to-arraybuffer":"^1.0.0","string-to-jsdoc-comment":"^1.0.0","typescript":"^3.3.1","webpack":"^4.0.0","webpack-bundle-analyzer":"^3.0.0","webpack-cli":"^3.0.0"},"types":"index.d.ts","scripts":{"coverage":"nyc report --reporter=html && open coverage/index.html","lint":"prettier --check '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","lint:fix":"prettier --write '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json","pretest":"npm run -s lint","test":"nyc mocha test/mocha-node-setup.js \"test/*/**/*-test.js\"","test:browser":"cypress run --browser chrome","build":"npm-run-all build:*","build:ts":"npm run -s update-endpoints:typescript","prebuild:browser":"mkdirp dist/","build:browser":"npm-run-all build:browser:*","build:browser:development":"webpack --mode development --entry . --output-library=Octokit --output=./dist/octokit-rest.js --profile --json > dist/bundle-stats.json","build:browser:production":"webpack --mode production --entry . --plugin=compression-webpack-plugin --output-library=Octokit --output-path=./dist --output-filename=octokit-rest.min.js --devtool source-map","generate-bundle-report":"webpack-bundle-analyzer dist/bundle-stats.json --mode=static --no-open --report dist/bundle-report.html","update-endpoints":"npm-run-all update-endpoints:*","update-endpoints:fetch-json":"node scripts/update-endpoints/fetch-json","update-endpoints:typescript":"node scripts/update-endpoints/typescript","prevalidate:ts":"npm run -s build:ts","validate:ts":"tsc --target es6 --noImplicitAny index.d.ts","postvalidate:ts":"tsc --noEmit --target es6 test/typescript-validate.ts","start-fixtures-server":"octokit-fixtures-server"},"license":"MIT","files":["index.js","index.d.ts","lib","plugins"],"nyc":{"ignore":["test"]},"release":{"publish":["@semantic-release/npm",{"path":"@semantic-release/github","assets":["dist/*","!dist/*.map.gz"]}]},"bundlesize":[{"path":"./dist/octokit-rest.min.js.gz","maxSize":"33 kB"}]}; /***/ }), @@ -4083,7 +4290,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var deprecation = __webpack_require__(692); -var once = _interopDefault(__webpack_require__(969)); +var once = _interopDefault(__webpack_require__(49)); const logOnce = once(deprecation => console.warn(deprecation)); /** @@ -4404,6 +4611,4168 @@ function applyAcceptHeader (res, headers) { /***/ }), /***/ 280: +/***/ (function(module) { + +module.exports = register; + +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + + if (!options) { + options = {}; + } + + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); + } + + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} + + +/***/ }), + +/***/ 284: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +// TODO: Update https://github.com/sindresorhus/get-stream +const getBuffer = async (stream) => { + const chunks = []; + let length = 0; + for await (const chunk of stream) { + chunks.push(chunk); + length += Buffer.byteLength(chunk); + } + if (Buffer.isBuffer(chunks[0])) { + return Buffer.concat(chunks, length); + } + return Buffer.from(chunks.join('')); +}; +exports.default = getBuffer; + + +/***/ }), + +/***/ 290: +/***/ (function(module) { + +"use strict"; + + +class QuickLRU { + constructor(options = {}) { + if (!(options.maxSize && options.maxSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + this.maxSize = options.maxSize; + this.onEviction = options.onEviction; + this.cache = new Map(); + this.oldCache = new Map(); + this._size = 0; + } + + _set(key, value) { + this.cache.set(key, value); + this._size++; + + if (this._size >= this.maxSize) { + this._size = 0; + + if (typeof this.onEviction === 'function') { + for (const [key, value] of this.oldCache.entries()) { + this.onEviction(key, value); + } + } + + this.oldCache = this.cache; + this.cache = new Map(); + } + } + + get(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + + if (this.oldCache.has(key)) { + const value = this.oldCache.get(key); + this.oldCache.delete(key); + this._set(key, value); + return value; + } + } + + set(key, value) { + if (this.cache.has(key)) { + this.cache.set(key, value); + } else { + this._set(key, value); + } + + return this; + } + + has(key) { + return this.cache.has(key) || this.oldCache.has(key); + } + + peek(key) { + if (this.cache.has(key)) { + return this.cache.get(key); + } + + if (this.oldCache.has(key)) { + return this.oldCache.get(key); + } + } + + delete(key) { + const deleted = this.cache.delete(key); + if (deleted) { + this._size--; + } + + return this.oldCache.delete(key) || deleted; + } + + clear() { + this.cache.clear(); + this.oldCache.clear(); + this._size = 0; + } + + * keys() { + for (const [key] of this) { + yield key; + } + } + + * values() { + for (const [, value] of this) { + yield value; + } + } + + * [Symbol.iterator]() { + for (const item of this.cache) { + yield item; + } + + for (const item of this.oldCache) { + const [key] = item; + if (!this.cache.has(key)) { + yield item; + } + } + } + + get size() { + let oldCacheSize = 0; + for (const key of this.oldCache.keys()) { + if (!this.cache.has(key)) { + oldCacheSize++; + } + } + + return Math.min(this._size + oldCacheSize, this.maxSize); + } +} + +module.exports = QuickLRU; + + +/***/ }), + +/***/ 291: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +function deepFreeze(object) { + for (const value of Object.values(object)) { + if (is_1.default.plainObject(value) || is_1.default.array(value)) { + deepFreeze(value); + } + } + return Object.freeze(object); +} +exports.default = deepFreeze; + + +/***/ }), + +/***/ 293: +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = authenticationRequestError; + +const { RequestError } = __webpack_require__(463); + +function authenticationRequestError(state, error, options) { + if (!error.headers) throw error; + + const otpRequired = /required/.test(error.headers["x-github-otp"] || ""); + // handle "2FA required" error only + if (error.status !== 401 || !otpRequired) { + throw error; + } + + if ( + error.status === 401 && + otpRequired && + error.request && + error.request.headers["x-github-otp"] + ) { + if (state.otp) { + delete state.otp; // no longer valid, request again + } else { + throw new RequestError( + "Invalid one-time password for two-factor authentication", + 401, + { + headers: error.headers, + request: options + } + ); + } + } + + if (typeof state.auth.on2fa !== "function") { + throw new RequestError( + "2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication", + 401, + { + headers: error.headers, + request: options + } + ); + } + + return Promise.resolve() + .then(() => { + return state.auth.on2fa(); + }) + .then(oneTimePassword => { + const newOptions = Object.assign(options, { + headers: Object.assign(options.headers, { + "x-github-otp": oneTimePassword + }) + }); + return state.octokit.request(newOptions).then(response => { + // If OTP still valid, then persist it for following requests + state.otp = oneTimePassword; + return response; + }); + }); +} + + +/***/ }), + +/***/ 294: +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = parseOptions; + +const { Deprecation } = __webpack_require__(692); +const { getUserAgent } = __webpack_require__(768); +const once = __webpack_require__(49); + +const pkg = __webpack_require__(215); + +const deprecateOptionsTimeout = once((log, deprecation) => + log.warn(deprecation) +); +const deprecateOptionsAgent = once((log, deprecation) => log.warn(deprecation)); +const deprecateOptionsHeaders = once((log, deprecation) => + log.warn(deprecation) +); + +function parseOptions(options, log, hook) { + if (options.headers) { + options.headers = Object.keys(options.headers).reduce((newObj, key) => { + newObj[key.toLowerCase()] = options.headers[key]; + return newObj; + }, {}); + } + + const clientDefaults = { + headers: options.headers || {}, + request: options.request || {}, + mediaType: { + previews: [], + format: "" + } + }; + + if (options.baseUrl) { + clientDefaults.baseUrl = options.baseUrl; + } + + if (options.userAgent) { + clientDefaults.headers["user-agent"] = options.userAgent; + } + + if (options.previews) { + clientDefaults.mediaType.previews = options.previews; + } + + if (options.timeZone) { + clientDefaults.headers["time-zone"] = options.timeZone; + } + + if (options.timeout) { + deprecateOptionsTimeout( + log, + new Deprecation( + "[@octokit/rest] new Octokit({timeout}) is deprecated. Use {request: {timeout}} instead. See https://github.com/octokit/request.js#request" + ) + ); + clientDefaults.request.timeout = options.timeout; + } + + if (options.agent) { + deprecateOptionsAgent( + log, + new Deprecation( + "[@octokit/rest] new Octokit({agent}) is deprecated. Use {request: {agent}} instead. See https://github.com/octokit/request.js#request" + ) + ); + clientDefaults.request.agent = options.agent; + } + + if (options.headers) { + deprecateOptionsHeaders( + log, + new Deprecation( + "[@octokit/rest] new Octokit({headers}) is deprecated. Use {userAgent, previews} instead. See https://github.com/octokit/request.js#request" + ) + ); + } + + const userAgentOption = clientDefaults.headers["user-agent"]; + const defaultUserAgent = `octokit.js/${pkg.version} ${getUserAgent()}`; + + clientDefaults.headers["user-agent"] = [userAgentOption, defaultUserAgent] + .filter(Boolean) + .join(" "); + + clientDefaults.request.hook = hook.bind(null, "request"); + + return clientDefaults; +} + + +/***/ }), + +/***/ 297: +/***/ (function(module) { + +module.exports = class HttpError extends Error { + constructor (message, code, headers) { + super(message) + + // Maintains proper stack trace (only available on V8) + /* istanbul ignore next */ + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor) + } + + this.name = 'HttpError' + this.code = code + this.headers = headers + } +} + + +/***/ }), + +/***/ 299: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +const VERSION = "1.1.2"; + +/** + * Some “list” response that can be paginated have a different response structure + * + * They have a `total_count` key in the response (search also has `incomplete_results`, + * /installation/repositories also has `repository_selection`), as well as a key with + * the list of the items which name varies from endpoint to endpoint: + * + * - https://developer.github.com/v3/search/#example (key `items`) + * - https://developer.github.com/v3/checks/runs/#response-3 (key: `check_runs`) + * - https://developer.github.com/v3/checks/suites/#response-1 (key: `check_suites`) + * - https://developer.github.com/v3/apps/installations/#list-repositories (key: `repositories`) + * - https://developer.github.com/v3/apps/installations/#list-installations-for-a-user (key `installations`) + * + * Octokit normalizes these responses so that paginated results are always returned following + * the same structure. One challenge is that if the list response has only one page, no Link + * header is provided, so this header alone is not sufficient to check wether a response is + * paginated or not. For the exceptions with the namespace, a fallback check for the route + * paths has to be added in order to normalize the response. We cannot check for the total_count + * property because it also exists in the response of Get the combined status for a specific ref. + */ +const REGEX = [/^\/search\//, /^\/repos\/[^/]+\/[^/]+\/commits\/[^/]+\/(check-runs|check-suites)([^/]|$)/, /^\/installation\/repositories([^/]|$)/, /^\/user\/installations([^/]|$)/, /^\/repos\/[^/]+\/[^/]+\/actions\/secrets([^/]|$)/, /^\/repos\/[^/]+\/[^/]+\/actions\/workflows(\/[^/]+\/runs)?([^/]|$)/, /^\/repos\/[^/]+\/[^/]+\/actions\/runs(\/[^/]+\/(artifacts|jobs))?([^/]|$)/]; +function normalizePaginatedListResponse(octokit, url, response) { + const path = url.replace(octokit.request.endpoint.DEFAULTS.baseUrl, ""); + const responseNeedsNormalization = REGEX.find(regex => regex.test(path)); + if (!responseNeedsNormalization) return; // keep the additional properties intact as there is currently no other way + // to retrieve the same information. + + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + + response.data.total_count = totalCount; + Object.defineProperty(response.data, namespaceKey, { + get() { + octokit.log.warn(`[@octokit/paginate-rest] "response.data.${namespaceKey}" is deprecated for "GET ${path}". Get the results directly from "response.data"`); + return Array.from(data); + } + + }); +} + +function iterator(octokit, route, parameters) { + const options = octokit.request.endpoint(route, parameters); + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + next() { + if (!url) { + return Promise.resolve({ + done: true + }); + } + + return octokit.request({ + method, + url, + headers + }).then(response => { + normalizePaginatedListResponse(octokit, url, response); // `response.headers.link` format: + // '; rel="next", ; rel="last"' + // sets `url` to undefined if "next" URL is not present or `link` header is not set + + url = ((response.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: response + }; + }); + } + + }) + }; +} + +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; + } + + return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); +} + +function gather(octokit, results, iterator, mapFn) { + return iterator.next().then(result => { + if (result.done) { + return results; + } + + let earlyExit = false; + + function done() { + earlyExit = true; + } + + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + + if (earlyExit) { + return results; + } + + return gather(octokit, results, iterator, mapFn); + }); +} + +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ + +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; + +exports.paginateRest = paginateRest; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 303: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const EventEmitter = __webpack_require__(614); +const JSONB = __webpack_require__(205); + +const loadStore = opts => { + const adapters = { + redis: '@keyv/redis', + mongodb: '@keyv/mongo', + mongo: '@keyv/mongo', + sqlite: '@keyv/sqlite', + postgresql: '@keyv/postgres', + postgres: '@keyv/postgres', + mysql: '@keyv/mysql' + }; + if (opts.adapter || opts.uri) { + const adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0]; + return new (require(adapters[adapter]))(opts); + } + + return new Map(); +}; + +class Keyv extends EventEmitter { + constructor(uri, opts) { + super(); + this.opts = Object.assign( + { + namespace: 'keyv', + serialize: JSONB.stringify, + deserialize: JSONB.parse + }, + (typeof uri === 'string') ? { uri } : uri, + opts + ); + + if (!this.opts.store) { + const adapterOpts = Object.assign({}, this.opts); + this.opts.store = loadStore(adapterOpts); + } + + if (typeof this.opts.store.on === 'function') { + this.opts.store.on('error', err => this.emit('error', err)); + } + + this.opts.store.namespace = this.opts.namespace; + } + + _getKeyPrefix(key) { + return `${this.opts.namespace}:${key}`; + } + + get(key, opts) { + const keyPrefixed = this._getKeyPrefix(key); + const { store } = this.opts; + return Promise.resolve() + .then(() => store.get(keyPrefixed)) + .then(data => { + return (typeof data === 'string') ? this.opts.deserialize(data) : data; + }) + .then(data => { + if (data === undefined) { + return undefined; + } + + if (typeof data.expires === 'number' && Date.now() > data.expires) { + this.delete(key); + return undefined; + } + + return (opts && opts.raw) ? data : data.value; + }); + } + + set(key, value, ttl) { + const keyPrefixed = this._getKeyPrefix(key); + if (typeof ttl === 'undefined') { + ttl = this.opts.ttl; + } + + if (ttl === 0) { + ttl = undefined; + } + + const { store } = this.opts; + + return Promise.resolve() + .then(() => { + const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; + value = { value, expires }; + return this.opts.serialize(value); + }) + .then(value => store.set(keyPrefixed, value, ttl)) + .then(() => true); + } + + delete(key) { + const keyPrefixed = this._getKeyPrefix(key); + const { store } = this.opts; + return Promise.resolve() + .then(() => store.delete(keyPrefixed)); + } + + clear() { + const { store } = this.opts; + return Promise.resolve() + .then(() => store.clear()); + } +} + +module.exports = Keyv; + + +/***/ }), + +/***/ 323: +/***/ (function(module) { + +"use strict"; + + +var isStream = module.exports = function (stream) { + return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; +}; + +isStream.writable = function (stream) { + return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; +}; + +isStream.readable = function (stream) { + return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; +}; + +isStream.duplex = function (stream) { + return isStream.writable(stream) && isStream.readable(stream); +}; + +isStream.transform = function (stream) { + return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; +}; + + +/***/ }), + +/***/ 325: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const PassThrough = __webpack_require__(413).PassThrough; +const mimicResponse = __webpack_require__(210); + +const cloneResponse = response => { + if (!(response && response.pipe)) { + throw new TypeError('Parameter `response` must be a response stream.'); + } + + const clone = new PassThrough(); + mimicResponse(response, clone); + + return response.pipe(clone); +}; + +module.exports = cloneResponse; + + +/***/ }), + +/***/ 336: +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = hasLastPage + +const deprecate = __webpack_require__(370) +const getPageLinks = __webpack_require__(577) + +function hasLastPage (link) { + deprecate(`octokit.hasLastPage() – You can use octokit.paginate or async iterators instead: https://github.com/octokit/rest.js#pagination.`) + return getPageLinks(link).last +} + + +/***/ }), + +/***/ 348: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +module.exports = validate; + +const { RequestError } = __webpack_require__(463); +const get = __webpack_require__(854); +const set = __webpack_require__(883); + +function validate(octokit, options) { + if (!options.request.validate) { + return; + } + const { validate: params } = options.request; + + Object.keys(params).forEach(parameterName => { + const parameter = get(params, parameterName); + + const expectedType = parameter.type; + let parentParameterName; + let parentValue; + let parentParamIsPresent = true; + let parentParameterIsArray = false; + + if (/\./.test(parameterName)) { + parentParameterName = parameterName.replace(/\.[^.]+$/, ""); + parentParameterIsArray = parentParameterName.slice(-2) === "[]"; + if (parentParameterIsArray) { + parentParameterName = parentParameterName.slice(0, -2); + } + parentValue = get(options, parentParameterName); + parentParamIsPresent = + parentParameterName === "headers" || + (typeof parentValue === "object" && parentValue !== null); + } + + const values = parentParameterIsArray + ? (get(options, parentParameterName) || []).map( + value => value[parameterName.split(/\./).pop()] + ) + : [get(options, parameterName)]; + + values.forEach((value, i) => { + const valueIsPresent = typeof value !== "undefined"; + const valueIsNull = value === null; + const currentParameterName = parentParameterIsArray + ? parameterName.replace(/\[\]/, `[${i}]`) + : parameterName; + + if (!parameter.required && !valueIsPresent) { + return; + } + + // if the parent parameter is of type object but allows null + // then the child parameters can be ignored + if (!parentParamIsPresent) { + return; + } + + if (parameter.allowNull && valueIsNull) { + return; + } + + if (!parameter.allowNull && valueIsNull) { + throw new RequestError( + `'${currentParameterName}' cannot be null`, + 400, + { + request: options + } + ); + } + + if (parameter.required && !valueIsPresent) { + throw new RequestError( + `Empty value for parameter '${currentParameterName}': ${JSON.stringify( + value + )}`, + 400, + { + request: options + } + ); + } + + // parse to integer before checking for enum + // so that string "1" will match enum with number 1 + if (expectedType === "integer") { + const unparsedValue = value; + value = parseInt(value, 10); + if (isNaN(value)) { + throw new RequestError( + `Invalid value for parameter '${currentParameterName}': ${JSON.stringify( + unparsedValue + )} is NaN`, + 400, + { + request: options + } + ); + } + } + + if (parameter.enum && parameter.enum.indexOf(String(value)) === -1) { + throw new RequestError( + `Invalid value for parameter '${currentParameterName}': ${JSON.stringify( + value + )}`, + 400, + { + request: options + } + ); + } + + if (parameter.validation) { + const regex = new RegExp(parameter.validation); + if (!regex.test(value)) { + throw new RequestError( + `Invalid value for parameter '${currentParameterName}': ${JSON.stringify( + value + )}`, + 400, + { + request: options + } + ); + } + } + + if (expectedType === "object" && typeof value === "string") { + try { + value = JSON.parse(value); + } catch (exception) { + throw new RequestError( + `JSON parse error of value for parameter '${currentParameterName}': ${JSON.stringify( + value + )}`, + 400, + { + request: options + } + ); + } + } + + set(options, parameter.mapTo || currentParameterName, value); + }); + }); + + return options; +} + + +/***/ }), + +/***/ 349: +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = authenticationRequestError; + +const { RequestError } = __webpack_require__(463); + +function authenticationRequestError(state, error, options) { + /* istanbul ignore next */ + if (!error.headers) throw error; + + const otpRequired = /required/.test(error.headers["x-github-otp"] || ""); + // handle "2FA required" error only + if (error.status !== 401 || !otpRequired) { + throw error; + } + + if ( + error.status === 401 && + otpRequired && + error.request && + error.request.headers["x-github-otp"] + ) { + throw new RequestError( + "Invalid one-time password for two-factor authentication", + 401, + { + headers: error.headers, + request: options + } + ); + } + + if (typeof state.auth.on2fa !== "function") { + throw new RequestError( + "2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication", + 401, + { + headers: error.headers, + request: options + } + ); + } + + return Promise.resolve() + .then(() => { + return state.auth.on2fa(); + }) + .then(oneTimePassword => { + const newOptions = Object.assign(options, { + headers: Object.assign( + { "x-github-otp": oneTimePassword }, + options.headers + ) + }); + return state.octokit.request(newOptions); + }); +} + + +/***/ }), + +/***/ 357: +/***/ (function(module) { + +module.exports = require("assert"); + +/***/ }), + +/***/ 368: +/***/ (function(module) { + +module.exports = function atob(str) { + return Buffer.from(str, 'base64').toString('binary') +} + + +/***/ }), + +/***/ 370: +/***/ (function(module) { + +module.exports = deprecate + +const loggedMessages = {} + +function deprecate (message) { + if (loggedMessages[message]) { + return + } + + console.warn(`DEPRECATED (@octokit/rest): ${message}`) + loggedMessages[message] = 1 +} + + +/***/ }), + +/***/ 385: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +var isPlainObject = __webpack_require__(3); +var universalUserAgent = __webpack_require__(796); + +function lowercaseKeys(object) { + if (!object) { + return {}; + } + + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach(key => { + if (isPlainObject.isPlainObject(options[key])) { + if (!(key in defaults)) Object.assign(result, { + [key]: options[key] + });else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { + [key]: options[key] + }); + } + }); + return result; +} + +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } + } + + return obj; +} + +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { + method, + url + } : { + url: method + }, options); + } else { + options = Object.assign({}, route); + } // lowercase header names before merging with defaults to avoid duplicates + + + options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging + + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten + + if (defaults && defaults.mediaType.previews.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + } + + mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); + return mergedOptions; +} + +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + + if (names.length === 0) { + return url; + } + + return url + separator + names.map(name => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +const urlVariableRegex = /\{[^}]+\}/g; + +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +} + +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); + + if (!matches) { + return []; + } + + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} + +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} + +// Based on https://github.com/bramstein/url-template, licensed under BSD +// TODO: create separate package. +// +// Copyright (c) 2012-2014, Bram Stein +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. The name of the author may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* istanbul ignore file */ +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + + return part; + }).join(""); +} + +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} + +function isDefined(value) { + return value !== undefined && value !== null; +} + +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} + +function getValues(context, operator, key, modifier) { + var value = context[key], + result = []; + + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + tmp.push(encodeValue(operator, value)); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + + return result; +} + +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} + +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + + expression.split(/,/g).forEach(function (variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + + if (operator && operator !== "+") { + var separator = ","; + + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + }); +} + +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible + + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later + + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + + const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + + if (!isBinaryRequest) { + if (options.mediaType.format) { + // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw + headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); + } + + if (options.mediaType.previews.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } // for GET/HEAD requests, set URL query parameters from remaining parameters + // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters + + + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } else { + headers["content-length"] = 0; + } + } + } // default content-type for JSON if body is set + + + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. + // fetch does not allow to set `content-length` header, but we can set body to an empty string + + + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } // Only return body/request keys if present + + + return Object.assign({ + method, + url, + headers + }, typeof body !== "undefined" ? { + body + } : null, options.request ? { + request: options.request + } : null); +} + +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} + +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS = merge(oldDefaults, newDefaults); + const endpoint = endpointWithDefaults.bind(null, DEFAULTS); + return Object.assign(endpoint, { + DEFAULTS, + defaults: withDefaults.bind(null, DEFAULTS), + merge: merge.bind(null, DEFAULTS), + parse + }); +} + +const VERSION = "6.0.11"; + +const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. +// So we use RequestParameters and add method as additional required property. + +const DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "", + previews: [] + } +}; + +const endpoint = withDefaults(null, DEFAULTS); + +exports.endpoint = endpoint; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 389: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const fs = __webpack_require__(747); +const shebangCommand = __webpack_require__(452); + +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + let buffer; + + if (Buffer.alloc) { + // Node.js v4.5+ / v5.10+ + buffer = Buffer.alloc(size); + } else { + // Old Node.js API + buffer = new Buffer(size); + buffer.fill(0); // zero-fill + } + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +module.exports = readShebang; + + +/***/ }), + +/***/ 390: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const EventEmitter = __webpack_require__(614); +const urlLib = __webpack_require__(835); +const normalizeUrl = __webpack_require__(53); +const getStream = __webpack_require__(145); +const CachePolicy = __webpack_require__(154); +const Response = __webpack_require__(93); +const lowercaseKeys = __webpack_require__(474); +const cloneResponse = __webpack_require__(325); +const Keyv = __webpack_require__(303); + +class CacheableRequest { + constructor(request, cacheAdapter) { + if (typeof request !== 'function') { + throw new TypeError('Parameter `request` must be a function'); + } + + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cacheable-request' + }); + + return this.createCacheableRequest(request); + } + + createCacheableRequest(request) { + return (opts, cb) => { + let url; + if (typeof opts === 'string') { + url = normalizeUrlObject(urlLib.parse(opts)); + opts = {}; + } else if (opts instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(opts.toString())); + opts = {}; + } else { + const [pathname, ...searchParts] = (opts.path || '').split('?'); + const search = searchParts.length > 0 ? + `?${searchParts.join('?')}` : + ''; + url = normalizeUrlObject({ ...opts, pathname, search }); + } + + opts = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...opts, + ...urlObjectToRequestOptions(url) + }; + opts.headers = lowercaseKeys(opts.headers); + + const ee = new EventEmitter(); + const normalizedUrlString = normalizeUrl( + urlLib.format(url), + { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false + } + ); + const key = `${opts.method}:${normalizedUrlString}`; + let revalidate = false; + let madeRequest = false; + + const makeRequest = opts => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback; + + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + + const handler = response => { + if (revalidate && !opts.forceRefresh) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); + if (!revalidatedPolicy.modified) { + const headers = revalidatedPolicy.policy.responseHeaders(); + response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(opts, response, opts); + response.fromCache = false; + } + + let clonedResponse; + if (opts.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + + (async () => { + try { + const bodyPromise = getStream.buffer(response); + + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)) + ]); + + if (requestErrored) { + return; + } + + const body = await bodyPromise; + + const value = { + cachePolicy: response.cachePolicy.toObject(), + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body + }; + + let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (opts.maxTtl) { + ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; + } + + await this.cache.set(key, value, ttl); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } else if (opts.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } + + ee.emit('response', clonedResponse || response); + if (typeof cb === 'function') { + cb(clonedResponse || response); + } + }; + + try { + const req = request(opts, handler); + req.once('error', requestErrorCallback); + req.once('abort', requestErrorCallback); + ee.emit('request', req); + } catch (error) { + ee.emit('error', new CacheableRequest.RequestError(error)); + } + }; + + (async () => { + const get = async opts => { + await Promise.resolve(); + + const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; + if (typeof cacheEntry === 'undefined') { + return makeRequest(opts); + } + + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { + const headers = policy.responseHeaders(); + const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); + response.cachePolicy = policy; + response.fromCache = true; + + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } else { + revalidate = cacheEntry; + opts.headers = policy.revalidationHeaders(opts); + makeRequest(opts); + } + }; + + const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); + this.cache.once('error', errorHandler); + ee.on('response', () => this.cache.removeListener('error', errorHandler)); + + try { + await get(opts); + } catch (error) { + if (opts.automaticFailover && !madeRequest) { + makeRequest(opts); + } + + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + + return ee; + }; + } +} + +function urlObjectToRequestOptions(url) { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +} + +function normalizeUrlObject(url) { + // If url was parsed by url.parse or new URL: + // - hostname will be set + // - host will be hostname[:port] + // - port will be set if it was explicit in the parsed string + // Otherwise, url was from request options: + // - hostname or host may be set + // - host shall not have port encoded + return { + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search + }; +} + +CacheableRequest.RequestError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'RequestError'; + Object.assign(this, error); + } +}; + +CacheableRequest.CacheError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'CacheError'; + Object.assign(this, error); + } +}; + +module.exports = CacheableRequest; + + +/***/ }), + +/***/ 393: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +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 __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const command_1 = __webpack_require__(431); +const file_command_1 = __webpack_require__(102); +const utils_1 = __webpack_require__(82); +const os = __importStar(__webpack_require__(87)); +const path = __importStar(__webpack_require__(622)); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + const delimiter = '_GitHubActionsFileCommandDelimeter_'; + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; + file_command_1.issueCommand('ENV', commandValue); + } + else { + command_1.issueCommand('set-env', { name }, convertedVal); + } +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueCommand('PATH', inputPath); + } + else { + command_1.issueCommand('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 402: +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = Octokit; + +const { request } = __webpack_require__(753); +const Hook = __webpack_require__(523); + +const parseClientOptions = __webpack_require__(294); + +function Octokit(plugins, options) { + options = options || {}; + const hook = new Hook.Collection(); + const log = Object.assign( + { + debug: () => {}, + info: () => {}, + warn: console.warn, + error: console.error + }, + options && options.log + ); + const api = { + hook, + log, + request: request.defaults(parseClientOptions(options, log, hook)) + }; + + plugins.forEach(pluginFunction => pluginFunction(api, options)); + + return api; +} + + +/***/ }), + +/***/ 407: +/***/ (function(module) { + +module.exports = require("buffer"); + +/***/ }), + +/***/ 413: +/***/ (function(module) { + +module.exports = require("stream"); + +/***/ }), + +/***/ 422: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isResponseOk = void 0; +exports.isResponseOk = (response) => { + const { statusCode } = response; + const limitStatusCode = response.request.options.followRedirect ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; +}; + + +/***/ }), + +/***/ 427: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +// Older verions of Node.js might not have `util.getSystemErrorName()`. +// In that case, fall back to a deprecated internal. +const util = __webpack_require__(669); + +let uv; + +if (typeof util.getSystemErrorName === 'function') { + module.exports = util.getSystemErrorName; +} else { + try { + uv = process.binding('uv'); + + if (typeof uv.errname !== 'function') { + throw new TypeError('uv.errname is not a function'); + } + } catch (err) { + console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); + uv = null; + } + + module.exports = code => errname(uv, code); +} + +// Used for testing the fallback behavior +module.exports.__test__ = errname; + +function errname(uv, code) { + if (uv) { + return uv.errname(code); + } + + if (!(code < 0)) { + throw new Error('err >= 0'); + } + + return `Unknown system error ${code}`; +} + + + +/***/ }), + +/***/ 430: +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = octokitValidate; + +const validate = __webpack_require__(348); + +function octokitValidate(octokit) { + octokit.hook.before("request", validate.bind(null, octokit)); +} + + +/***/ }), + +/***/ 431: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os = __importStar(__webpack_require__(87)); +const utils_1 = __webpack_require__(82); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 452: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +var shebangRegex = __webpack_require__(816); + +module.exports = function (str) { + var match = str.match(shebangRegex); + + if (!match) { + return null; + } + + var arr = match[0].replace(/#! ?/, '').split(' '); + var bin = arr[0].split('/').pop(); + var arg = arr[1]; + + return (bin === 'env' ? + arg : + bin + (arg ? ' ' + arg : '') + ); +}; + + +/***/ }), + +/***/ 453: +/***/ (function(module, __unusedexports, __webpack_require__) { + +var once = __webpack_require__(49) +var eos = __webpack_require__(9) +var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes + +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) + +var isFn = function (fn) { + return typeof fn === 'function' +} + +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} + +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} + +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) + + var closed = false + stream.on('close', function () { + closed = true + }) + + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) + + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) + } +} + +var call = function (fn) { + fn() +} + +var pipe = function (from, to) { + return from.pipe(to) +} + +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') + + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) + + return streams.reduce(pipe) +} + +module.exports = pump + + +/***/ }), + +/***/ 454: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(__webpack_require__(413)); +var http = _interopDefault(__webpack_require__(605)); +var Url = _interopDefault(__webpack_require__(835)); +var https = _interopDefault(__webpack_require__(211)); +var zlib = _interopDefault(__webpack_require__(761)); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = __webpack_require__(18).convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; + + +/***/ }), + +/***/ 460: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +exports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); + + +/***/ }), + +/***/ 462: +/***/ (function(module) { + +"use strict"; + + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; + + +/***/ }), + +/***/ 463: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var deprecation = __webpack_require__(692); +var once = _interopDefault(__webpack_require__(49)); + +const logOnce = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ + +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options + + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } + +} + +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 469: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +// Originally pulled from https://github.com/JasonEtco/actions-toolkit/blob/master/src/github.ts +const graphql_1 = __webpack_require__(898); +const rest_1 = __webpack_require__(0); +const Context = __importStar(__webpack_require__(262)); +const httpClient = __importStar(__webpack_require__(539)); +// We need this in order to extend Octokit +rest_1.Octokit.prototype = new rest_1.Octokit(); +exports.context = new Context.Context(); +class GitHub extends rest_1.Octokit { + constructor(token, opts) { + super(GitHub.getOctokitOptions(GitHub.disambiguate(token, opts))); + this.graphql = GitHub.getGraphQL(GitHub.disambiguate(token, opts)); + } + /** + * Disambiguates the constructor overload parameters + */ + static disambiguate(token, opts) { + return [ + typeof token === 'string' ? token : '', + typeof token === 'object' ? token : opts || {} + ]; + } + static getOctokitOptions(args) { + const token = args[0]; + const options = Object.assign({}, args[1]); // Shallow clone - don't mutate the object provided by the caller + // Base URL - GHES or Dotcom + options.baseUrl = options.baseUrl || this.getApiBaseUrl(); + // Auth + const auth = GitHub.getAuthString(token, options); + if (auth) { + options.auth = auth; + } + // Proxy + const agent = GitHub.getProxyAgent(options.baseUrl, options); + if (agent) { + // Shallow clone - don't mutate the object provided by the caller + options.request = options.request ? Object.assign({}, options.request) : {}; + // Set the agent + options.request.agent = agent; + } + return options; + } + static getGraphQL(args) { + const defaults = {}; + defaults.baseUrl = this.getGraphQLBaseUrl(); + const token = args[0]; + const options = args[1]; + // Authorization + const auth = this.getAuthString(token, options); + if (auth) { + defaults.headers = { + authorization: auth + }; + } + // Proxy + const agent = GitHub.getProxyAgent(defaults.baseUrl, options); + if (agent) { + defaults.request = { agent }; + } + return graphql_1.graphql.defaults(defaults); + } + static getAuthString(token, options) { + // Validate args + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; + } + static getProxyAgent(destinationUrl, options) { + var _a; + if (!((_a = options.request) === null || _a === void 0 ? void 0 : _a.agent)) { + if (httpClient.getProxyUrl(destinationUrl)) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); + } + } + return undefined; + } + static getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; + } + static getGraphQLBaseUrl() { + let url = process.env['GITHUB_GRAPHQL_URL'] || 'https://api.github.com/graphql'; + // Shouldn't be a trailing slash, but remove if so + if (url.endsWith('/')) { + url = url.substr(0, url.length - 1); + } + // Remove trailing "/graphql" + if (url.toUpperCase().endsWith('/GRAPHQL')) { + url = url.substr(0, url.length - '/graphql'.length); + } + return url; + } +} +exports.GitHub = GitHub; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 470: /***/ (function(module, exports) { exports = module.exports = SemVer @@ -5891,4203 +10260,6 @@ function coerce (version) { } -/***/ }), - -/***/ 290: -/***/ (function(module) { - -"use strict"; - - -class QuickLRU { - constructor(options = {}) { - if (!(options.maxSize && options.maxSize > 0)) { - throw new TypeError('`maxSize` must be a number greater than 0'); - } - - this.maxSize = options.maxSize; - this.onEviction = options.onEviction; - this.cache = new Map(); - this.oldCache = new Map(); - this._size = 0; - } - - _set(key, value) { - this.cache.set(key, value); - this._size++; - - if (this._size >= this.maxSize) { - this._size = 0; - - if (typeof this.onEviction === 'function') { - for (const [key, value] of this.oldCache.entries()) { - this.onEviction(key, value); - } - } - - this.oldCache = this.cache; - this.cache = new Map(); - } - } - - get(key) { - if (this.cache.has(key)) { - return this.cache.get(key); - } - - if (this.oldCache.has(key)) { - const value = this.oldCache.get(key); - this.oldCache.delete(key); - this._set(key, value); - return value; - } - } - - set(key, value) { - if (this.cache.has(key)) { - this.cache.set(key, value); - } else { - this._set(key, value); - } - - return this; - } - - has(key) { - return this.cache.has(key) || this.oldCache.has(key); - } - - peek(key) { - if (this.cache.has(key)) { - return this.cache.get(key); - } - - if (this.oldCache.has(key)) { - return this.oldCache.get(key); - } - } - - delete(key) { - const deleted = this.cache.delete(key); - if (deleted) { - this._size--; - } - - return this.oldCache.delete(key) || deleted; - } - - clear() { - this.cache.clear(); - this.oldCache.clear(); - this._size = 0; - } - - * keys() { - for (const [key] of this) { - yield key; - } - } - - * values() { - for (const [, value] of this) { - yield value; - } - } - - * [Symbol.iterator]() { - for (const item of this.cache) { - yield item; - } - - for (const item of this.oldCache) { - const [key] = item; - if (!this.cache.has(key)) { - yield item; - } - } - } - - get size() { - let oldCacheSize = 0; - for (const key of this.oldCache.keys()) { - if (!this.cache.has(key)) { - oldCacheSize++; - } - } - - return Math.min(this._size + oldCacheSize, this.maxSize); - } -} - -module.exports = QuickLRU; - - -/***/ }), - -/***/ 291: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __webpack_require__(534); -function deepFreeze(object) { - for (const value of Object.values(object)) { - if (is_1.default.plainObject(value) || is_1.default.array(value)) { - deepFreeze(value); - } - } - return Object.freeze(object); -} -exports.default = deepFreeze; - - -/***/ }), - -/***/ 293: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = authenticationRequestError; - -const { RequestError } = __webpack_require__(463); - -function authenticationRequestError(state, error, options) { - if (!error.headers) throw error; - - const otpRequired = /required/.test(error.headers["x-github-otp"] || ""); - // handle "2FA required" error only - if (error.status !== 401 || !otpRequired) { - throw error; - } - - if ( - error.status === 401 && - otpRequired && - error.request && - error.request.headers["x-github-otp"] - ) { - if (state.otp) { - delete state.otp; // no longer valid, request again - } else { - throw new RequestError( - "Invalid one-time password for two-factor authentication", - 401, - { - headers: error.headers, - request: options - } - ); - } - } - - if (typeof state.auth.on2fa !== "function") { - throw new RequestError( - "2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication", - 401, - { - headers: error.headers, - request: options - } - ); - } - - return Promise.resolve() - .then(() => { - return state.auth.on2fa(); - }) - .then(oneTimePassword => { - const newOptions = Object.assign(options, { - headers: Object.assign(options.headers, { - "x-github-otp": oneTimePassword - }) - }); - return state.octokit.request(newOptions).then(response => { - // If OTP still valid, then persist it for following requests - state.otp = oneTimePassword; - return response; - }); - }); -} - - -/***/ }), - -/***/ 294: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = parseOptions; - -const { Deprecation } = __webpack_require__(692); -const { getUserAgent } = __webpack_require__(619); -const once = __webpack_require__(969); - -const pkg = __webpack_require__(215); - -const deprecateOptionsTimeout = once((log, deprecation) => - log.warn(deprecation) -); -const deprecateOptionsAgent = once((log, deprecation) => log.warn(deprecation)); -const deprecateOptionsHeaders = once((log, deprecation) => - log.warn(deprecation) -); - -function parseOptions(options, log, hook) { - if (options.headers) { - options.headers = Object.keys(options.headers).reduce((newObj, key) => { - newObj[key.toLowerCase()] = options.headers[key]; - return newObj; - }, {}); - } - - const clientDefaults = { - headers: options.headers || {}, - request: options.request || {}, - mediaType: { - previews: [], - format: "" - } - }; - - if (options.baseUrl) { - clientDefaults.baseUrl = options.baseUrl; - } - - if (options.userAgent) { - clientDefaults.headers["user-agent"] = options.userAgent; - } - - if (options.previews) { - clientDefaults.mediaType.previews = options.previews; - } - - if (options.timeZone) { - clientDefaults.headers["time-zone"] = options.timeZone; - } - - if (options.timeout) { - deprecateOptionsTimeout( - log, - new Deprecation( - "[@octokit/rest] new Octokit({timeout}) is deprecated. Use {request: {timeout}} instead. See https://github.com/octokit/request.js#request" - ) - ); - clientDefaults.request.timeout = options.timeout; - } - - if (options.agent) { - deprecateOptionsAgent( - log, - new Deprecation( - "[@octokit/rest] new Octokit({agent}) is deprecated. Use {request: {agent}} instead. See https://github.com/octokit/request.js#request" - ) - ); - clientDefaults.request.agent = options.agent; - } - - if (options.headers) { - deprecateOptionsHeaders( - log, - new Deprecation( - "[@octokit/rest] new Octokit({headers}) is deprecated. Use {userAgent, previews} instead. See https://github.com/octokit/request.js#request" - ) - ); - } - - const userAgentOption = clientDefaults.headers["user-agent"]; - const defaultUserAgent = `octokit.js/${pkg.version} ${getUserAgent()}`; - - clientDefaults.headers["user-agent"] = [userAgentOption, defaultUserAgent] - .filter(Boolean) - .join(" "); - - clientDefaults.request.hook = hook.bind(null, "request"); - - return clientDefaults; -} - - -/***/ }), - -/***/ 297: -/***/ (function(module) { - -module.exports = class HttpError extends Error { - constructor (message, code, headers) { - super(message) - - // Maintains proper stack trace (only available on V8) - /* istanbul ignore next */ - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor) - } - - this.name = 'HttpError' - this.code = code - this.headers = headers - } -} - - -/***/ }), - -/***/ 299: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -const VERSION = "1.1.2"; - -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint: - * - * - https://developer.github.com/v3/search/#example (key `items`) - * - https://developer.github.com/v3/checks/runs/#response-3 (key: `check_runs`) - * - https://developer.github.com/v3/checks/suites/#response-1 (key: `check_suites`) - * - https://developer.github.com/v3/apps/installations/#list-repositories (key: `repositories`) - * - https://developer.github.com/v3/apps/installations/#list-installations-for-a-user (key `installations`) - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. For the exceptions with the namespace, a fallback check for the route - * paths has to be added in order to normalize the response. We cannot check for the total_count - * property because it also exists in the response of Get the combined status for a specific ref. - */ -const REGEX = [/^\/search\//, /^\/repos\/[^/]+\/[^/]+\/commits\/[^/]+\/(check-runs|check-suites)([^/]|$)/, /^\/installation\/repositories([^/]|$)/, /^\/user\/installations([^/]|$)/, /^\/repos\/[^/]+\/[^/]+\/actions\/secrets([^/]|$)/, /^\/repos\/[^/]+\/[^/]+\/actions\/workflows(\/[^/]+\/runs)?([^/]|$)/, /^\/repos\/[^/]+\/[^/]+\/actions\/runs(\/[^/]+\/(artifacts|jobs))?([^/]|$)/]; -function normalizePaginatedListResponse(octokit, url, response) { - const path = url.replace(octokit.request.endpoint.DEFAULTS.baseUrl, ""); - const responseNeedsNormalization = REGEX.find(regex => regex.test(path)); - if (!responseNeedsNormalization) return; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - - response.data.total_count = totalCount; - Object.defineProperty(response.data, namespaceKey, { - get() { - octokit.log.warn(`[@octokit/paginate-rest] "response.data.${namespaceKey}" is deprecated for "GET ${path}". Get the results directly from "response.data"`); - return Array.from(data); - } - - }); -} - -function iterator(octokit, route, parameters) { - const options = octokit.request.endpoint(route, parameters); - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - next() { - if (!url) { - return Promise.resolve({ - done: true - }); - } - - return octokit.request({ - method, - url, - headers - }).then(response => { - normalizePaginatedListResponse(octokit, url, response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set - - url = ((response.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: response - }; - }); - } - - }) - }; -} - -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; - } - - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); -} - -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { - if (result.done) { - return results; - } - - let earlyExit = false; - - function done() { - earlyExit = true; - } - - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - - if (earlyExit) { - return results; - } - - return gather(octokit, results, iterator, mapFn); - }); -} - -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; - -exports.paginateRest = paginateRest; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 303: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const EventEmitter = __webpack_require__(614); -const JSONB = __webpack_require__(205); - -const loadStore = opts => { - const adapters = { - redis: '@keyv/redis', - mongodb: '@keyv/mongo', - mongo: '@keyv/mongo', - sqlite: '@keyv/sqlite', - postgresql: '@keyv/postgres', - postgres: '@keyv/postgres', - mysql: '@keyv/mysql' - }; - if (opts.adapter || opts.uri) { - const adapter = opts.adapter || /^[^:]*/.exec(opts.uri)[0]; - return new (require(adapters[adapter]))(opts); - } - - return new Map(); -}; - -class Keyv extends EventEmitter { - constructor(uri, opts) { - super(); - this.opts = Object.assign( - { - namespace: 'keyv', - serialize: JSONB.stringify, - deserialize: JSONB.parse - }, - (typeof uri === 'string') ? { uri } : uri, - opts - ); - - if (!this.opts.store) { - const adapterOpts = Object.assign({}, this.opts); - this.opts.store = loadStore(adapterOpts); - } - - if (typeof this.opts.store.on === 'function') { - this.opts.store.on('error', err => this.emit('error', err)); - } - - this.opts.store.namespace = this.opts.namespace; - } - - _getKeyPrefix(key) { - return `${this.opts.namespace}:${key}`; - } - - get(key, opts) { - const keyPrefixed = this._getKeyPrefix(key); - const { store } = this.opts; - return Promise.resolve() - .then(() => store.get(keyPrefixed)) - .then(data => { - return (typeof data === 'string') ? this.opts.deserialize(data) : data; - }) - .then(data => { - if (data === undefined) { - return undefined; - } - - if (typeof data.expires === 'number' && Date.now() > data.expires) { - this.delete(key); - return undefined; - } - - return (opts && opts.raw) ? data : data.value; - }); - } - - set(key, value, ttl) { - const keyPrefixed = this._getKeyPrefix(key); - if (typeof ttl === 'undefined') { - ttl = this.opts.ttl; - } - - if (ttl === 0) { - ttl = undefined; - } - - const { store } = this.opts; - - return Promise.resolve() - .then(() => { - const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; - value = { value, expires }; - return this.opts.serialize(value); - }) - .then(value => store.set(keyPrefixed, value, ttl)) - .then(() => true); - } - - delete(key) { - const keyPrefixed = this._getKeyPrefix(key); - const { store } = this.opts; - return Promise.resolve() - .then(() => store.delete(keyPrefixed)); - } - - clear() { - const { store } = this.opts; - return Promise.resolve() - .then(() => store.clear()); - } -} - -module.exports = Keyv; - - -/***/ }), - -/***/ 323: -/***/ (function(module) { - -"use strict"; - - -var isStream = module.exports = function (stream) { - return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; -}; - -isStream.writable = function (stream) { - return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; -}; - -isStream.readable = function (stream) { - return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; -}; - -isStream.duplex = function (stream) { - return isStream.writable(stream) && isStream.readable(stream); -}; - -isStream.transform = function (stream) { - return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; -}; - - -/***/ }), - -/***/ 325: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const PassThrough = __webpack_require__(413).PassThrough; -const mimicResponse = __webpack_require__(210); - -const cloneResponse = response => { - if (!(response && response.pipe)) { - throw new TypeError('Parameter `response` must be a response stream.'); - } - - const clone = new PassThrough(); - mimicResponse(response, clone); - - return response.pipe(clone); -}; - -module.exports = cloneResponse; - - -/***/ }), - -/***/ 336: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = hasLastPage - -const deprecate = __webpack_require__(370) -const getPageLinks = __webpack_require__(577) - -function hasLastPage (link) { - deprecate(`octokit.hasLastPage() – You can use octokit.paginate or async iterators instead: https://github.com/octokit/rest.js#pagination.`) - return getPageLinks(link).last -} - - -/***/ }), - -/***/ 348: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -module.exports = validate; - -const { RequestError } = __webpack_require__(463); -const get = __webpack_require__(854); -const set = __webpack_require__(883); - -function validate(octokit, options) { - if (!options.request.validate) { - return; - } - const { validate: params } = options.request; - - Object.keys(params).forEach(parameterName => { - const parameter = get(params, parameterName); - - const expectedType = parameter.type; - let parentParameterName; - let parentValue; - let parentParamIsPresent = true; - let parentParameterIsArray = false; - - if (/\./.test(parameterName)) { - parentParameterName = parameterName.replace(/\.[^.]+$/, ""); - parentParameterIsArray = parentParameterName.slice(-2) === "[]"; - if (parentParameterIsArray) { - parentParameterName = parentParameterName.slice(0, -2); - } - parentValue = get(options, parentParameterName); - parentParamIsPresent = - parentParameterName === "headers" || - (typeof parentValue === "object" && parentValue !== null); - } - - const values = parentParameterIsArray - ? (get(options, parentParameterName) || []).map( - value => value[parameterName.split(/\./).pop()] - ) - : [get(options, parameterName)]; - - values.forEach((value, i) => { - const valueIsPresent = typeof value !== "undefined"; - const valueIsNull = value === null; - const currentParameterName = parentParameterIsArray - ? parameterName.replace(/\[\]/, `[${i}]`) - : parameterName; - - if (!parameter.required && !valueIsPresent) { - return; - } - - // if the parent parameter is of type object but allows null - // then the child parameters can be ignored - if (!parentParamIsPresent) { - return; - } - - if (parameter.allowNull && valueIsNull) { - return; - } - - if (!parameter.allowNull && valueIsNull) { - throw new RequestError( - `'${currentParameterName}' cannot be null`, - 400, - { - request: options - } - ); - } - - if (parameter.required && !valueIsPresent) { - throw new RequestError( - `Empty value for parameter '${currentParameterName}': ${JSON.stringify( - value - )}`, - 400, - { - request: options - } - ); - } - - // parse to integer before checking for enum - // so that string "1" will match enum with number 1 - if (expectedType === "integer") { - const unparsedValue = value; - value = parseInt(value, 10); - if (isNaN(value)) { - throw new RequestError( - `Invalid value for parameter '${currentParameterName}': ${JSON.stringify( - unparsedValue - )} is NaN`, - 400, - { - request: options - } - ); - } - } - - if (parameter.enum && parameter.enum.indexOf(String(value)) === -1) { - throw new RequestError( - `Invalid value for parameter '${currentParameterName}': ${JSON.stringify( - value - )}`, - 400, - { - request: options - } - ); - } - - if (parameter.validation) { - const regex = new RegExp(parameter.validation); - if (!regex.test(value)) { - throw new RequestError( - `Invalid value for parameter '${currentParameterName}': ${JSON.stringify( - value - )}`, - 400, - { - request: options - } - ); - } - } - - if (expectedType === "object" && typeof value === "string") { - try { - value = JSON.parse(value); - } catch (exception) { - throw new RequestError( - `JSON parse error of value for parameter '${currentParameterName}': ${JSON.stringify( - value - )}`, - 400, - { - request: options - } - ); - } - } - - set(options, parameter.mapTo || currentParameterName, value); - }); - }); - - return options; -} - - -/***/ }), - -/***/ 349: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = authenticationRequestError; - -const { RequestError } = __webpack_require__(463); - -function authenticationRequestError(state, error, options) { - /* istanbul ignore next */ - if (!error.headers) throw error; - - const otpRequired = /required/.test(error.headers["x-github-otp"] || ""); - // handle "2FA required" error only - if (error.status !== 401 || !otpRequired) { - throw error; - } - - if ( - error.status === 401 && - otpRequired && - error.request && - error.request.headers["x-github-otp"] - ) { - throw new RequestError( - "Invalid one-time password for two-factor authentication", - 401, - { - headers: error.headers, - request: options - } - ); - } - - if (typeof state.auth.on2fa !== "function") { - throw new RequestError( - "2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication", - 401, - { - headers: error.headers, - request: options - } - ); - } - - return Promise.resolve() - .then(() => { - return state.auth.on2fa(); - }) - .then(oneTimePassword => { - const newOptions = Object.assign(options, { - headers: Object.assign( - { "x-github-otp": oneTimePassword }, - options.headers - ) - }); - return state.octokit.request(newOptions); - }); -} - - -/***/ }), - -/***/ 357: -/***/ (function(module) { - -module.exports = require("assert"); - -/***/ }), - -/***/ 363: -/***/ (function(module) { - -module.exports = register - -function register (state, name, method, options) { - if (typeof method !== 'function') { - throw new Error('method for before hook must be a function') - } - - if (!options) { - options = {} - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options) - }, method)() - } - - return Promise.resolve() - .then(function () { - if (!state.registry[name]) { - return method(options) - } - - return (state.registry[name]).reduce(function (method, registered) { - return registered.hook.bind(null, method, options) - }, method)() - }) -} - - -/***/ }), - -/***/ 368: -/***/ (function(module) { - -module.exports = function atob(str) { - return Buffer.from(str, 'base64').toString('binary') -} - - -/***/ }), - -/***/ 370: -/***/ (function(module) { - -module.exports = deprecate - -const loggedMessages = {} - -function deprecate (message) { - if (loggedMessages[message]) { - return - } - - console.warn(`DEPRECATED (@octokit/rest): ${message}`) - loggedMessages[message] = 1 -} - - -/***/ }), - -/***/ 385: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var isPlainObject = _interopDefault(__webpack_require__(626)); -var universalUserAgent = __webpack_require__(796); - -function lowercaseKeys(object) { - if (!object) { - return {}; - } - - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} - -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject(options[key])) { - if (!(key in defaults)) Object.assign(result, { - [key]: options[key] - });else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { - [key]: options[key] - }); - } - }); - return result; -} - -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); - } else { - options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - - - options.headers = lowercaseKeys(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); - } - - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); - return mergedOptions; -} - -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - - if (names.length === 0) { - return url; - } - - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -const urlVariableRegex = /\{[^}]+\}/g; - -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} - -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - - if (!matches) { - return []; - } - - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} - -function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); -} - -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* istanbul ignore file */ -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - - return part; - }).join(""); -} - -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} - -function isDefined(value) { - return value !== undefined && value !== null; -} - -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} - -function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; - - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - - return result; -} - -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} - -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - - expression.split(/,/g).forEach(function (variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - - if (operator && operator !== "+") { - var separator = ","; - - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - }); -} - -function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{+$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later - - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequset = /application\/octet-stream/i.test(headers.accept); - - if (!isBinaryRequset) { - if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); - } - - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters - - - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } else { - headers["content-length"] = 0; - } - } - } // default content-type for JSON if body is set - - - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string - - - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present - - - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); -} - -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), - parse - }); -} - -const VERSION = "6.0.3"; - -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. - -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; - -const endpoint = withDefaults(null, DEFAULTS); - -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 389: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(747); -const shebangCommand = __webpack_require__(866); - -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - let buffer; - - if (Buffer.alloc) { - // Node.js v4.5+ / v5.10+ - buffer = Buffer.alloc(size); - } else { - // Old Node.js API - buffer = new Buffer(size); - buffer.fill(0); // zero-fill - } - - let fd; - - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } - - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} - -module.exports = readShebang; - - -/***/ }), - -/***/ 390: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -const EventEmitter = __webpack_require__(614); -const urlLib = __webpack_require__(835); -const normalizeUrl = __webpack_require__(53); -const getStream = __webpack_require__(145); -const CachePolicy = __webpack_require__(154); -const Response = __webpack_require__(93); -const lowercaseKeys = __webpack_require__(474); -const cloneResponse = __webpack_require__(325); -const Keyv = __webpack_require__(303); - -class CacheableRequest { - constructor(request, cacheAdapter) { - if (typeof request !== 'function') { - throw new TypeError('Parameter `request` must be a function'); - } - - this.cache = new Keyv({ - uri: typeof cacheAdapter === 'string' && cacheAdapter, - store: typeof cacheAdapter !== 'string' && cacheAdapter, - namespace: 'cacheable-request' - }); - - return this.createCacheableRequest(request); - } - - createCacheableRequest(request) { - return (opts, cb) => { - let url; - if (typeof opts === 'string') { - url = normalizeUrlObject(urlLib.parse(opts)); - opts = {}; - } else if (opts instanceof urlLib.URL) { - url = normalizeUrlObject(urlLib.parse(opts.toString())); - opts = {}; - } else { - const [pathname, ...searchParts] = (opts.path || '').split('?'); - const search = searchParts.length > 0 ? - `?${searchParts.join('?')}` : - ''; - url = normalizeUrlObject({ ...opts, pathname, search }); - } - - opts = { - headers: {}, - method: 'GET', - cache: true, - strictTtl: false, - automaticFailover: false, - ...opts, - ...urlObjectToRequestOptions(url) - }; - opts.headers = lowercaseKeys(opts.headers); - - const ee = new EventEmitter(); - const normalizedUrlString = normalizeUrl( - urlLib.format(url), - { - stripWWW: false, - removeTrailingSlash: false, - stripAuthentication: false - } - ); - const key = `${opts.method}:${normalizedUrlString}`; - let revalidate = false; - let madeRequest = false; - - const makeRequest = opts => { - madeRequest = true; - let requestErrored = false; - let requestErrorCallback; - - const requestErrorPromise = new Promise(resolve => { - requestErrorCallback = () => { - if (!requestErrored) { - requestErrored = true; - resolve(); - } - }; - }); - - const handler = response => { - if (revalidate && !opts.forceRefresh) { - response.status = response.statusCode; - const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); - if (!revalidatedPolicy.modified) { - const headers = revalidatedPolicy.policy.responseHeaders(); - response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); - response.cachePolicy = revalidatedPolicy.policy; - response.fromCache = true; - } - } - - if (!response.fromCache) { - response.cachePolicy = new CachePolicy(opts, response, opts); - response.fromCache = false; - } - - let clonedResponse; - if (opts.cache && response.cachePolicy.storable()) { - clonedResponse = cloneResponse(response); - - (async () => { - try { - const bodyPromise = getStream.buffer(response); - - await Promise.race([ - requestErrorPromise, - new Promise(resolve => response.once('end', resolve)) - ]); - - if (requestErrored) { - return; - } - - const body = await bodyPromise; - - const value = { - cachePolicy: response.cachePolicy.toObject(), - url: response.url, - statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, - body - }; - - let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; - if (opts.maxTtl) { - ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; - } - - await this.cache.set(key, value, ttl); - } catch (error) { - ee.emit('error', new CacheableRequest.CacheError(error)); - } - })(); - } else if (opts.cache && revalidate) { - (async () => { - try { - await this.cache.delete(key); - } catch (error) { - ee.emit('error', new CacheableRequest.CacheError(error)); - } - })(); - } - - ee.emit('response', clonedResponse || response); - if (typeof cb === 'function') { - cb(clonedResponse || response); - } - }; - - try { - const req = request(opts, handler); - req.once('error', requestErrorCallback); - req.once('abort', requestErrorCallback); - ee.emit('request', req); - } catch (error) { - ee.emit('error', new CacheableRequest.RequestError(error)); - } - }; - - (async () => { - const get = async opts => { - await Promise.resolve(); - - const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; - if (typeof cacheEntry === 'undefined') { - return makeRequest(opts); - } - - const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); - if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { - const headers = policy.responseHeaders(); - const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); - response.cachePolicy = policy; - response.fromCache = true; - - ee.emit('response', response); - if (typeof cb === 'function') { - cb(response); - } - } else { - revalidate = cacheEntry; - opts.headers = policy.revalidationHeaders(opts); - makeRequest(opts); - } - }; - - const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); - this.cache.once('error', errorHandler); - ee.on('response', () => this.cache.removeListener('error', errorHandler)); - - try { - await get(opts); - } catch (error) { - if (opts.automaticFailover && !madeRequest) { - makeRequest(opts); - } - - ee.emit('error', new CacheableRequest.CacheError(error)); - } - })(); - - return ee; - }; - } -} - -function urlObjectToRequestOptions(url) { - const options = { ...url }; - options.path = `${url.pathname || '/'}${url.search || ''}`; - delete options.pathname; - delete options.search; - return options; -} - -function normalizeUrlObject(url) { - // If url was parsed by url.parse or new URL: - // - hostname will be set - // - host will be hostname[:port] - // - port will be set if it was explicit in the parsed string - // Otherwise, url was from request options: - // - hostname or host may be set - // - host shall not have port encoded - return { - protocol: url.protocol, - auth: url.auth, - hostname: url.hostname || url.host || 'localhost', - port: url.port, - pathname: url.pathname, - search: url.search - }; -} - -CacheableRequest.RequestError = class extends Error { - constructor(error) { - super(error.message); - this.name = 'RequestError'; - Object.assign(this, error); - } -}; - -CacheableRequest.CacheError = class extends Error { - constructor(error) { - super(error.message); - this.name = 'CacheError'; - Object.assign(this, error); - } -}; - -module.exports = CacheableRequest; - - -/***/ }), - -/***/ 402: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = Octokit; - -const { request } = __webpack_require__(753); -const Hook = __webpack_require__(523); - -const parseClientOptions = __webpack_require__(294); - -function Octokit(plugins, options) { - options = options || {}; - const hook = new Hook.Collection(); - const log = Object.assign( - { - debug: () => {}, - info: () => {}, - warn: console.warn, - error: console.error - }, - options && options.log - ); - const api = { - hook, - log, - request: request.defaults(parseClientOptions(options, log, hook)) - }; - - plugins.forEach(pluginFunction => pluginFunction(api, options)); - - return api; -} - - -/***/ }), - -/***/ 413: -/***/ (function(module) { - -module.exports = require("stream"); - -/***/ }), - -/***/ 427: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -// Older verions of Node.js might not have `util.getSystemErrorName()`. -// In that case, fall back to a deprecated internal. -const util = __webpack_require__(669); - -let uv; - -if (typeof util.getSystemErrorName === 'function') { - module.exports = util.getSystemErrorName; -} else { - try { - uv = process.binding('uv'); - - if (typeof uv.errname !== 'function') { - throw new TypeError('uv.errname is not a function'); - } - } catch (err) { - console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); - uv = null; - } - - module.exports = code => errname(uv, code); -} - -// Used for testing the fallback behavior -module.exports.__test__ = errname; - -function errname(uv, code) { - if (uv) { - return uv.errname(code); - } - - if (!(code < 0)) { - throw new Error('err >= 0'); - } - - return `Unknown system error ${code}`; -} - - - -/***/ }), - -/***/ 430: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = octokitValidate; - -const validate = __webpack_require__(348); - -function octokitValidate(octokit) { - octokit.hook.before("request", validate.bind(null, octokit)); -} - - -/***/ }), - -/***/ 431: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const os = __importStar(__webpack_require__(87)); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -function escapeData(s) { - return toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map - -/***/ }), - -/***/ 453: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var once = __webpack_require__(969) -var eos = __webpack_require__(9) -var fs = __webpack_require__(747) // we only need fs to get the ReadStream and WriteStream prototypes - -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) - -var isFn = function (fn) { - return typeof fn === 'function' -} - -var isFS = function (stream) { - if (!ancient) return false // newer node version do not need to care about fs is a special way - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) -} - -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} - -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) - - var closed = false - stream.on('close', function () { - closed = true - }) - - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) - - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true - - if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want - - if (isFn(stream.destroy)) return stream.destroy() - - callback(err || new Error('stream was destroyed')) - } -} - -var call = function (fn) { - fn() -} - -var pipe = function (from, to) { - return from.pipe(to) -} - -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') - - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) - - return streams.reduce(pipe) -} - -module.exports = pump - - -/***/ }), - -/***/ 454: -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__webpack_require__(413)); -var http = _interopDefault(__webpack_require__(605)); -var Url = _interopDefault(__webpack_require__(835)); -var https = _interopDefault(__webpack_require__(211)); -var zlib = _interopDefault(__webpack_require__(761)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); - - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} - -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); - -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ - -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); - - this.message = message; - this.type = type; - - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = __webpack_require__(18).convert; -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; - -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } - - this[INTERNALS].disturbed = true; - - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; - - return new Body.Promise(function (resolve, reject) { - let resTimeout; - - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } - - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } - - accumBytes += chunk.length; - accum.push(chunk); - }); - - body.on('end', function () { - if (abort) { - return; - } - - clearTimeout(resTimeout); - - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} - -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} - -const INTERNAL = Symbol('internal'); - -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} - -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } - - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; -} - -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; - -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); - -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); - -const INTERNALS$2 = Symbol('Request internals'); - -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} - -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parse_url(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parse_url(`${input}`); - } - input = {}; - } else { - parsedURL = parse_url(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } - - get redirect() { - return this[INTERNALS$2].redirect; - } - - get signal() { - return this[INTERNALS$2].signal; - } - - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} - -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} - -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ - -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); - - this.type = 'aborted'; - this.message = message; - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; - -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; -const resolve_url = Url.resolve; - -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - - Body.Promise = fetch.Promise; - - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); - - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - - let response = null; - - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - - // send request - const req = send(options); - let reqTimeout; - - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } - - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } - - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } - - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); - }); - - req.on('response', function (res) { - clearTimeout(reqTimeout); - - const headers = createHeadersLenient(res.headers); - - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); - - // HTTP fetch step 5.3 - const locationURL = location === null ? null : resolve_url(request.url, location); - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout - }; - - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } - - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } - - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); - - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; - - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); - - // HTTP-network fetch step 12.1.1.4: handle content codings - - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } - - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; - - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } - - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - return; - } - - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } - - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); - - writeToStream(req, request); - }); -} -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; - -// expose Promise -fetch.Promise = global.Promise; - -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; - - -/***/ }), - -/***/ 460: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __webpack_require__(534); -exports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); - - -/***/ }), - -/***/ 462: -/***/ (function(module) { - -"use strict"; - - -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; - -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - return arg; -} - -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; - - // Algorithm below is based on https://qntm.org/cmd - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = `"${arg}"`; - - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); - } - - return arg; -} - -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; - - -/***/ }), - -/***/ 463: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var deprecation = __webpack_require__(692); -var once = _interopDefault(__webpack_require__(969)); - -const logOnce = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = "HttpError"; - this.status = statusCode; - Object.defineProperty(this, "code", { - get() { - logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - this.headers = options.headers || {}; // redact request credentials without mutating original request options - - const requestCopy = Object.assign({}, options.request); - - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") - }); - } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; - } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 468: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __webpack_require__(534); -const types_1 = __webpack_require__(36); -const core_1 = __webpack_require__(946); -if (!core_1.knownHookEvents.includes('beforeRetry')) { - core_1.knownHookEvents.push('beforeRetry', 'afterResponse'); -} -exports.knownBodyTypes = ['json', 'buffer', 'text']; -// @ts-ignore The error is: Not all code paths return a value. -exports.parseBody = (response, responseType, parseJson, encoding) => { - const { rawBody } = response; - try { - if (responseType === 'text') { - return rawBody.toString(encoding); - } - if (responseType === 'json') { - return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); - } - if (responseType === 'buffer') { - return Buffer.from(rawBody); - } - throw new types_1.ParseError({ - message: `Unknown body type '${responseType}'`, - name: 'Error' - }, response); - } - catch (error) { - throw new types_1.ParseError(error, response); - } -}; -class PromisableRequest extends core_1.default { - static normalizeArguments(url, nonNormalizedOptions, defaults) { - const options = super.normalizeArguments(url, nonNormalizedOptions, defaults); - if (is_1.default.null_(options.encoding)) { - throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); - } - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); - // `options.responseType` - if (options.responseType === undefined) { - options.responseType = 'text'; - } - // `options.retry` - const { retry } = options; - if (defaults) { - options.retry = { ...defaults.retry }; - } - else { - options.retry = { - calculateDelay: retryObject => retryObject.computedValue, - limit: 0, - methods: [], - statusCodes: [], - errorCodes: [], - maxRetryAfter: undefined - }; - } - if (is_1.default.object(retry)) { - options.retry = { - ...options.retry, - ...retry - }; - options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; - options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; - options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; - } - else if (is_1.default.number(retry)) { - options.retry.limit = retry; - } - if (is_1.default.undefined(options.retry.maxRetryAfter)) { - options.retry.maxRetryAfter = Math.min(...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); - } - // `options.pagination` - if (is_1.default.object(options.pagination)) { - if (defaults) { - options.pagination = { - ...defaults.pagination, - ...options.pagination - }; - } - const { pagination } = options; - if (!is_1.default.function_(pagination.transform)) { - throw new Error('`options.pagination.transform` must be implemented'); - } - if (!is_1.default.function_(pagination.shouldContinue)) { - throw new Error('`options.pagination.shouldContinue` must be implemented'); - } - if (!is_1.default.function_(pagination.filter)) { - throw new TypeError('`options.pagination.filter` must be implemented'); - } - if (!is_1.default.function_(pagination.paginate)) { - throw new Error('`options.pagination.paginate` must be implemented'); - } - } - // JSON mode - if (options.responseType === 'json' && options.headers.accept === undefined) { - options.headers.accept = 'application/json'; - } - return options; - } - static mergeOptions(...sources) { - let mergedOptions; - for (const source of sources) { - mergedOptions = PromisableRequest.normalizeArguments(undefined, source, mergedOptions); - } - return mergedOptions; - } - async _beforeError(error) { - if (!(error instanceof core_1.RequestError)) { - error = new core_1.RequestError(error.message, error, this); - } - // Let the promise decide whether to abort or not - // It is also responsible for the `beforeError` hook - this.emit('error', error); - } -} -exports.default = PromisableRequest; - - -/***/ }), - -/***/ 469: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -// Originally pulled from https://github.com/JasonEtco/actions-toolkit/blob/master/src/github.ts -const graphql_1 = __webpack_require__(898); -const rest_1 = __webpack_require__(0); -const Context = __importStar(__webpack_require__(262)); -const httpClient = __importStar(__webpack_require__(539)); -// We need this in order to extend Octokit -rest_1.Octokit.prototype = new rest_1.Octokit(); -exports.context = new Context.Context(); -class GitHub extends rest_1.Octokit { - constructor(token, opts) { - super(GitHub.getOctokitOptions(GitHub.disambiguate(token, opts))); - this.graphql = GitHub.getGraphQL(GitHub.disambiguate(token, opts)); - } - /** - * Disambiguates the constructor overload parameters - */ - static disambiguate(token, opts) { - return [ - typeof token === 'string' ? token : '', - typeof token === 'object' ? token : opts || {} - ]; - } - static getOctokitOptions(args) { - const token = args[0]; - const options = Object.assign({}, args[1]); // Shallow clone - don't mutate the object provided by the caller - // Base URL - GHES or Dotcom - options.baseUrl = options.baseUrl || this.getApiBaseUrl(); - // Auth - const auth = GitHub.getAuthString(token, options); - if (auth) { - options.auth = auth; - } - // Proxy - const agent = GitHub.getProxyAgent(options.baseUrl, options); - if (agent) { - // Shallow clone - don't mutate the object provided by the caller - options.request = options.request ? Object.assign({}, options.request) : {}; - // Set the agent - options.request.agent = agent; - } - return options; - } - static getGraphQL(args) { - const defaults = {}; - defaults.baseUrl = this.getGraphQLBaseUrl(); - const token = args[0]; - const options = args[1]; - // Authorization - const auth = this.getAuthString(token, options); - if (auth) { - defaults.headers = { - authorization: auth - }; - } - // Proxy - const agent = GitHub.getProxyAgent(defaults.baseUrl, options); - if (agent) { - defaults.request = { agent }; - } - return graphql_1.graphql.defaults(defaults); - } - static getAuthString(token, options) { - // Validate args - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; - } - static getProxyAgent(destinationUrl, options) { - var _a; - if (!((_a = options.request) === null || _a === void 0 ? void 0 : _a.agent)) { - if (httpClient.getProxyUrl(destinationUrl)) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); - } - } - return undefined; - } - static getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; - } - static getGraphQLBaseUrl() { - let url = process.env['GITHUB_GRAPHQL_URL'] || 'https://api.github.com/graphql'; - // Shouldn't be a trailing slash, but remove if so - if (url.endsWith('/')) { - url = url.substr(0, url.length - 1); - } - // Remove trailing "/graphql" - if (url.toUpperCase().endsWith('/GRAPHQL')) { - url = url.substr(0, url.length - '/graphql'.length); - } - return url; - } -} -exports.GitHub = GitHub; -//# sourceMappingURL=github.js.map - -/***/ }), - -/***/ 470: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const command_1 = __webpack_require__(431); -const os = __importStar(__webpack_require__(87)); -const path = __importStar(__webpack_require__(622)); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = command_1.toCommandValue(val); - process.env[name] = convertedVal; - command_1.issueCommand('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - command_1.issueCommand('add-path', {}, inputPath); - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. The value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - command_1.issueCommand('set-output', { name }, value); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds an warning issue - * @param message warning issue message. Errors will be converted to string via toString() - */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -//# sourceMappingURL=core.js.map - /***/ }), /***/ 471: @@ -10336,6 +10508,66 @@ module.exports = timer; module.exports.default = timer; +/***/ }), + +/***/ 494: +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +const os = __webpack_require__(87); +const execa = __webpack_require__(955); + +// Reference: https://www.gaijin.at/en/lstwinver.php +const names = new Map([ + ['10.0', '10'], + ['6.3', '8.1'], + ['6.2', '8'], + ['6.1', '7'], + ['6.0', 'Vista'], + ['5.2', 'Server 2003'], + ['5.1', 'XP'], + ['5.0', '2000'], + ['4.9', 'ME'], + ['4.1', '98'], + ['4.0', '95'] +]); + +const windowsRelease = release => { + const version = /\d+\.\d/.exec(release || os.release()); + + if (release && !version) { + throw new Error('`release` argument doesn\'t match `n.n`'); + } + + const ver = (version || [])[0]; + + // Server 2008, 2012, 2016, and 2019 versions are ambiguous with desktop versions and must be detected at runtime. + // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version + // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx + // If `wmic` is obsoloete (later versions of Windows 10), use PowerShell instead. + // If the resulting caption contains the year 2008, 2012, 2016 or 2019, it is a server version, so return a server OS name. + if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) { + let stdout; + try { + stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; + } catch (_) { + stdout = execa.sync('powershell', ['(Get-CimInstance -ClassName Win32_OperatingSystem).caption']).stdout || ''; + } + + const year = (stdout.match(/2008|2012|2016|2019/) || [])[0]; + + if (year) { + return `Server ${year}`; + } + } + + return names.get(ver); +}; + +module.exports = windowsRelease; + + /***/ }), /***/ 507: @@ -10374,51 +10606,51 @@ module.exports = url => { /***/ 510: /***/ (function(module) { -module.exports = addHook +module.exports = addHook; -function addHook (state, kind, name, hook) { - var orig = hook +function addHook(state, kind, name, hook) { + var orig = hook; if (!state.registry[name]) { - state.registry[name] = [] + state.registry[name] = []; } - if (kind === 'before') { + if (kind === "before") { hook = function (method, options) { return Promise.resolve() .then(orig.bind(null, options)) - .then(method.bind(null, options)) - } + .then(method.bind(null, options)); + }; } - if (kind === 'after') { + if (kind === "after") { hook = function (method, options) { - var result + var result; return Promise.resolve() .then(method.bind(null, options)) .then(function (result_) { - result = result_ - return orig(result, options) + result = result_; + return orig(result, options); }) .then(function () { - return result - }) - } + return result; + }); + }; } - if (kind === 'error') { + if (kind === "error") { hook = function (method, options) { return Promise.resolve() .then(method.bind(null, options)) .catch(function (error) { - return orig(error, options) - }) - } + return orig(error, options); + }); + }; } state.registry[name].push({ hook: hook, - orig: orig - }) + orig: orig, + }); } @@ -10427,9 +10659,9 @@ function addHook (state, kind, name, hook) { /***/ 523: /***/ (function(module, __unusedexports, __webpack_require__) { -var register = __webpack_require__(363) +var register = __webpack_require__(280) var addHook = __webpack_require__(510) -var removeHook = __webpack_require__(763) +var removeHook = __webpack_require__(866) // bind with array of arguments: https://stackoverflow.com/a/21792913 var bind = Function.bind @@ -10531,49 +10763,108 @@ module.exports = factory(); /// /// Object.defineProperty(exports, "__esModule", { value: true }); +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', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'HTMLElement', + ...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 isOfType = (type) => (value) => typeof value === type; const getObjectType = (value) => { - const objectName = toString.call(value).slice(8, -1); - if (objectName) { - return objectName; + 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) { - switch (value) { - case null: - return "null" /* null */; - case true: - case false: - return "boolean" /* boolean */; - default: + if (value === null) { + return 'null'; } switch (typeof value) { case 'undefined': - return "undefined" /* undefined */; + return 'undefined'; case 'string': - return "string" /* string */; + return 'string'; case 'number': - return "number" /* number */; + return 'number'; + case 'boolean': + return 'boolean'; + case 'function': + return 'Function'; case 'bigint': - return "bigint" /* bigint */; + return 'bigint'; case 'symbol': - return "symbol" /* symbol */; + return 'symbol'; default: } - if (is.function_(value)) { - return "Function" /* Function */; - } if (is.observable(value)) { - return "Observable" /* Observable */; + return 'Observable'; } if (is.array(value)) { - return "Array" /* Array */; + return 'Array'; } if (is.buffer(value)) { - return "Buffer" /* Buffer */; + return 'Buffer'; } const tagType = getObjectType(value); if (tagType) { @@ -10582,7 +10873,7 @@ function is(value) { if (value instanceof String || value instanceof Boolean || value instanceof Number) { throw new TypeError('Please don\'t use object wrappers for primitive types'); } - return "Object" /* Object */; + return 'Object'; } is.undefined = isOfType('undefined'); is.string = isOfType('string'); @@ -10596,7 +10887,15 @@ 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 = Array.isArray; +is.array = (value, assertion) => { + if (!Array.isArray(value)) { + return false; + } + if (!is.function_(assertion)) { + return true; + } + return value.every(assertion); +}; is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); @@ -10604,41 +10903,41 @@ is.iterable = (value) => { var _a; return is.function_((_a = value) === null || is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[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" /* Promise */)(value); +is.nativePromise = (value) => isObjectOfType('Promise')(value); const hasPromiseAPI = (value) => { var _a, _b; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); }; is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); -is.generatorFunction = isObjectOfType("GeneratorFunction" /* GeneratorFunction */); -is.asyncGeneratorFunction = (value) => getObjectType(value) === "AsyncGeneratorFunction" /* AsyncGeneratorFunction */; -is.asyncFunction = (value) => getObjectType(value) === "AsyncFunction" /* AsyncFunction */; +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" /* RegExp */); -is.date = isObjectOfType("Date" /* Date */); -is.error = isObjectOfType("Error" /* Error */); -is.map = (value) => isObjectOfType("Map" /* Map */)(value); -is.set = (value) => isObjectOfType("Set" /* Set */)(value); -is.weakMap = (value) => isObjectOfType("WeakMap" /* WeakMap */)(value); -is.weakSet = (value) => isObjectOfType("WeakSet" /* WeakSet */)(value); -is.int8Array = isObjectOfType("Int8Array" /* Int8Array */); -is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */); -is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */); -is.int16Array = isObjectOfType("Int16Array" /* Int16Array */); -is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */); -is.int32Array = isObjectOfType("Int32Array" /* Int32Array */); -is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */); -is.float32Array = isObjectOfType("Float32Array" /* Float32Array */); -is.float64Array = isObjectOfType("Float64Array" /* Float64Array */); -is.bigInt64Array = isObjectOfType("BigInt64Array" /* BigInt64Array */); -is.bigUint64Array = isObjectOfType("BigUint64Array" /* BigUint64Array */); -is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */); -is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */); -is.dataView = isObjectOfType("DataView" /* DataView */); +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); +is.weakSet = (value) => isObjectOfType('WeakSet')(value); +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'); is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; -is.urlInstance = (value) => isObjectOfType("URL" /* URL */)(value); +is.urlInstance = (value) => isObjectOfType('URL')(value); is.urlString = (value) => { if (!is.string(value)) { return false; @@ -10657,45 +10956,18 @@ is.truthy = (value) => Boolean(value); // Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` is.falsy = (value) => !value; is.nan = (value) => Number.isNaN(value); -const primitiveTypeOfTypes = new Set([ - 'undefined', - 'string', - 'number', - 'bigint', - 'boolean', - 'symbol' -]); -is.primitive = (value) => is.null_(value) || primitiveTypeOfTypes.has(typeof 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/master/index.js - if (getObjectType(value) !== "Object" /* Object */) { + if (toString.call(value) !== '[object Object]') { return false; } const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.getPrototypeOf({}); }; -const typedArrayTypes = new Set([ - "Int8Array" /* Int8Array */, - "Uint8Array" /* Uint8Array */, - "Uint8ClampedArray" /* Uint8ClampedArray */, - "Int16Array" /* Int16Array */, - "Uint16Array" /* Uint16Array */, - "Int32Array" /* Int32Array */, - "Uint32Array" /* Uint32Array */, - "Float32Array" /* Float32Array */, - "Float64Array" /* Float64Array */, - "BigInt64Array" /* BigInt64Array */, - "BigUint64Array" /* BigUint64Array */ -]); -is.typedArray = (value) => { - const objectType = getObjectType(value); - if (objectType === undefined) { - return false; - } - return typedArrayTypes.has(objectType); -}; +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.inRange = (value, range) => { @@ -10715,8 +10987,13 @@ const DOM_PROPERTIES_TO_CHECK = [ '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.domElement = (value) => { + return 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) => { var _a, _b, _c, _d; if (!value) { @@ -10772,55 +11049,61 @@ const assertType = (condition, description, value) => { }; exports.assert = { // Unknowns. - undefined: (value) => assertType(is.undefined(value), "undefined" /* undefined */, value), - string: (value) => assertType(is.string(value), "string" /* string */, value), - number: (value) => assertType(is.number(value), "number" /* number */, value), - bigint: (value) => assertType(is.bigint(value), "bigint" /* bigint */, value), + undefined: (value) => assertType(is.undefined(value), 'undefined', value), + string: (value) => assertType(is.string(value), 'string', value), + number: (value) => assertType(is.number(value), 'number', value), + bigint: (value) => assertType(is.bigint(value), 'bigint', value), // eslint-disable-next-line @typescript-eslint/ban-types - function_: (value) => assertType(is.function_(value), "Function" /* Function */, value), - null_: (value) => assertType(is.null_(value), "null" /* null */, value), + function_: (value) => assertType(is.function_(value), 'Function', value), + null_: (value) => assertType(is.null_(value), 'null', value), class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), - boolean: (value) => assertType(is.boolean(value), "boolean" /* boolean */, value), - symbol: (value) => assertType(is.symbol(value), "symbol" /* symbol */, 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" /* numericString */, value), - array: (value) => assertType(is.array(value), "Array" /* Array */, value), - buffer: (value) => assertType(is.buffer(value), "Buffer" /* Buffer */, value), + array: (value, assertion) => { + const assert = assertType; + assert(is.array(value), 'Array', value); + if (assertion) { + value.forEach(assertion); + } + }, + buffer: (value) => assertType(is.buffer(value), 'Buffer', value), nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), - object: (value) => assertType(is.object(value), "Object" /* Object */, value), + object: (value) => assertType(is.object(value), 'Object', value), iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), - generator: (value) => assertType(is.generator(value), "Generator" /* Generator */, value), - asyncGenerator: (value) => assertType(is.asyncGenerator(value), "AsyncGenerator" /* AsyncGenerator */, 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" /* nativePromise */, value), - promise: (value) => assertType(is.promise(value), "Promise" /* Promise */, value), - generatorFunction: (value) => assertType(is.generatorFunction(value), "GeneratorFunction" /* GeneratorFunction */, value), - asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), "AsyncGeneratorFunction" /* AsyncGeneratorFunction */, 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" /* AsyncFunction */, value), + asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), // eslint-disable-next-line @typescript-eslint/ban-types - boundFunction: (value) => assertType(is.boundFunction(value), "Function" /* Function */, value), - regExp: (value) => assertType(is.regExp(value), "RegExp" /* RegExp */, value), - date: (value) => assertType(is.date(value), "Date" /* Date */, value), - error: (value) => assertType(is.error(value), "Error" /* Error */, value), - map: (value) => assertType(is.map(value), "Map" /* Map */, value), - set: (value) => assertType(is.set(value), "Set" /* Set */, value), - weakMap: (value) => assertType(is.weakMap(value), "WeakMap" /* WeakMap */, value), - weakSet: (value) => assertType(is.weakSet(value), "WeakSet" /* WeakSet */, value), - int8Array: (value) => assertType(is.int8Array(value), "Int8Array" /* Int8Array */, value), - uint8Array: (value) => assertType(is.uint8Array(value), "Uint8Array" /* Uint8Array */, value), - uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), "Uint8ClampedArray" /* Uint8ClampedArray */, value), - int16Array: (value) => assertType(is.int16Array(value), "Int16Array" /* Int16Array */, value), - uint16Array: (value) => assertType(is.uint16Array(value), "Uint16Array" /* Uint16Array */, value), - int32Array: (value) => assertType(is.int32Array(value), "Int32Array" /* Int32Array */, value), - uint32Array: (value) => assertType(is.uint32Array(value), "Uint32Array" /* Uint32Array */, value), - float32Array: (value) => assertType(is.float32Array(value), "Float32Array" /* Float32Array */, value), - float64Array: (value) => assertType(is.float64Array(value), "Float64Array" /* Float64Array */, value), - bigInt64Array: (value) => assertType(is.bigInt64Array(value), "BigInt64Array" /* BigInt64Array */, value), - bigUint64Array: (value) => assertType(is.bigUint64Array(value), "BigUint64Array" /* BigUint64Array */, value), - arrayBuffer: (value) => assertType(is.arrayBuffer(value), "ArrayBuffer" /* ArrayBuffer */, value), - sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), "SharedArrayBuffer" /* SharedArrayBuffer */, value), - dataView: (value) => assertType(is.dataView(value), "DataView" /* DataView */, value), - urlInstance: (value) => assertType(is.urlInstance(value), "URL" /* URL */, value), + 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), + 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), + urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), @@ -10831,8 +11114,8 @@ exports.assert = { plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), - domElement: (value) => assertType(is.domElement(value), "Element" /* domElement */, value), - observable: (value) => assertType(is.observable(value), "Observable" /* Observable */, value), + domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), + observable: (value) => assertType(is.observable(value), 'Observable', value), nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), @@ -10911,7 +11194,6 @@ function hasFirstPage (link) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const url = __webpack_require__(835); const http = __webpack_require__(605); const https = __webpack_require__(211); const pm = __webpack_require__(950); @@ -10960,7 +11242,7 @@ var MediaTypes; * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); + let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; @@ -10979,6 +11261,15 @@ const HttpResponseRetryCodes = [ const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; @@ -10997,7 +11288,7 @@ class HttpClientResponse { } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { - let parsedUrl = url.parse(requestUrl); + let parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; @@ -11102,7 +11393,7 @@ class HttpClient { if (this._disposed) { throw new Error('Client has already been disposed.'); } - let parsedUrl = url.parse(requestUrl); + let parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 @@ -11141,7 +11432,7 @@ class HttpClient { // if there's no location to redirect to, we won't break; } - let parsedRedirectUrl = url.parse(redirectUrl); + let parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { @@ -11257,7 +11548,7 @@ class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { - let parsedUrl = url.parse(serverUrl); + let parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { @@ -11330,7 +11621,9 @@ class HttpClient { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { - proxyAuth: proxyUrl.auth, + ...((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), host: proxyUrl.hostname, port: proxyUrl.port } @@ -11425,12 +11718,8 @@ class HttpClient { else { msg = 'Failed request: (' + statusCode + ')'; } - let err = new Error(msg); - // attach statusCode and body obj (if available) to the error object - err['statusCode'] = statusCode; - if (response.result) { - err['result'] = response.result; - } + let err = new HttpClientError(msg, statusCode); + err.result = response.result; reject(err); } else { @@ -11442,62 +11731,6 @@ class HttpClient { exports.HttpClient = HttpClient; -/***/ }), - -/***/ 548: -/***/ (function(module) { - -"use strict"; - - -/*! - * isobject - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(val) { - return val != null && typeof val === 'object' && Array.isArray(val) === false; -} - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObjectObject(o) { - return isObject(o) === true - && Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObjectObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; - - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; -} - -module.exports = isPlainObject; - - /***/ }), /***/ 550: @@ -11552,8 +11785,10 @@ class PCancelable { this._reject = reject; const onResolve = value => { - this._isPending = false; - resolve(value); + if (!this._isCanceled || !onCancel.shouldReject) { + this._isPending = false; + resolve(value); + } }; const onReject = error => { @@ -11600,6 +11835,8 @@ class PCancelable { return; } + this._isCanceled = true; + if (this._cancelHandlers.length > 0) { try { for (const handler of this._cancelHandlers) { @@ -11607,10 +11844,10 @@ class PCancelable { } } catch (error) { this._reject(error); + return; } } - this._isCanceled = true; if (this._rejectOnCancel) { this._reject(new CancelError(reason)); } @@ -11677,7 +11914,7 @@ const niceTry = __webpack_require__(948); const resolveCommand = __webpack_require__(489); const escape = __webpack_require__(462); const readShebang = __webpack_require__(389); -const semver = __webpack_require__(280); +const semver = __webpack_require__(470); const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; @@ -12011,7 +12248,11 @@ class CacheableLookup { const newPromise = this.queryAndCache(hostname); this._pending[hostname] = newPromise; - cached = await newPromise; + try { + cached = await newPromise; + } finally { + delete this._pending[hostname]; + } } } @@ -12125,29 +12366,21 @@ class CacheableLookup { return this._dnsLookup(hostname, all); } - try { - let query = await this._resolve(hostname); + let query = await this._resolve(hostname); - if (query.entries.length === 0 && this._fallback) { - query = await this._lookup(hostname); + if (query.entries.length === 0 && this._fallback) { + query = await this._lookup(hostname); - if (query.entries.length !== 0) { - // Use `dns.lookup(...)` for that particular hostname - this._hostnamesToFallback.add(hostname); - } + if (query.entries.length !== 0) { + // Use `dns.lookup(...)` for that particular hostname + this._hostnamesToFallback.add(hostname); } - - const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; - await this._set(hostname, query.entries, cacheTtl); - - delete this._pending[hostname]; - - return query.entries; - } catch (error) { - delete this._pending[hostname]; - - throw error; } + + const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; + await this._set(hostname, query.entries, cacheTtl); + + return query.entries; } _tick(ms) { @@ -12267,6 +12500,43 @@ function getPageLinks (link) { } +/***/ }), + +/***/ 594: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.retryAfterStatusCodes = void 0; +exports.retryAfterStatusCodes = new Set([413, 429, 503]); +const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => { + if (attemptCount > retryOptions.limit) { + return 0; + } + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = retryOptions.errorCodes.includes(error.code); + const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (error.response) { + if (retryAfter) { + if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) { + return 0; + } + return retryAfter; + } + if (error.response.statusCode === 413) { + return 0; + } + } + const noise = Math.random() * 100; + return ((2 ** (attemptCount - 1)) * 1000) + noise; +}; +exports.default = calculateRetryDelay; + + /***/ }), /***/ 605: @@ -12281,36 +12551,6 @@ module.exports = require("http"); module.exports = require("events"); -/***/ }), - -/***/ 619: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var osName = _interopDefault(__webpack_require__(2)); - -function getUserAgent() { - try { - return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`; - } catch (error) { - if (/wmic os get Caption/.test(error.message)) { - return "Windows "; - } - - throw error; - } -} - -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 621: @@ -12424,62 +12664,6 @@ module.exports = options => { }; -/***/ }), - -/***/ 626: -/***/ (function(module) { - -"use strict"; - - -/*! - * isobject - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(val) { - return val != null && typeof val === 'object' && Array.isArray(val) === false; -} - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObjectObject(o) { - return isObject(o) === true - && Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObjectObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; - - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; -} - -module.exports = isPlainObject; - - /***/ }), /***/ 628: @@ -12512,6 +12696,29 @@ exports.default = default_1; module.exports = require("net"); +/***/ }), + +/***/ 639: +/***/ (function(module) { + +"use strict"; + +module.exports = function (x) { + var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); + var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); + + if (x[x.length - 1] === lf) { + x = x.slice(0, x.length - 1); + } + + if (x[x.length - 1] === cr) { + x = x.slice(0, x.length - 1); + } + + return x; +}; + + /***/ }), /***/ 649: @@ -12601,7 +12808,7 @@ module.exports = require("util"); module.exports = authenticate; const { Deprecation } = __webpack_require__(692); -const once = __webpack_require__(969); +const once = __webpack_require__(49); const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation)); @@ -12766,6 +12973,52 @@ makeError(TypeError, 'ERR_INVALID_CHAR', args => { }); +/***/ }), + +/***/ 701: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} + +function isPlainObject(o) { + var ctor,prot; + + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +} + +exports.isPlainObject = isPlainObject; + + /***/ }), /***/ 723: @@ -12795,6 +13048,7 @@ module.exports = header => { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0; const conversionTable = { auto: 0, ipv4: 4, @@ -12997,18 +13251,18 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var endpoint = __webpack_require__(385); var universalUserAgent = __webpack_require__(796); -var isPlainObject = _interopDefault(__webpack_require__(548)); +var isPlainObject = __webpack_require__(701); var nodeFetch = _interopDefault(__webpack_require__(454)); var requestError = __webpack_require__(257); -const VERSION = "5.4.5"; +const VERSION = "5.4.14"; function getBufferResponse(response) { return response.arrayBuffer(); } function fetchWrapper(requestOptions) { - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } @@ -13146,51 +13400,34 @@ exports.request = request; module.exports = require("zlib"); -/***/ }), - -/***/ 763: -/***/ (function(module) { - -module.exports = removeHook - -function removeHook (state, name, method) { - if (!state.registry[name]) { - return - } - - var index = state.registry[name] - .map(function (registered) { return registered.orig }) - .indexOf(method) - - if (index === -1) { - return - } - - state.registry[name].splice(index, 1) -} - - /***/ }), /***/ 768: -/***/ (function(module) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -module.exports = function (x) { - var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); - var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); - if (x[x.length - 1] === lf) { - x = x.slice(0, x.length - 1); - } +Object.defineProperty(exports, '__esModule', { value: true }); - if (x[x.length - 1] === cr) { - x = x.slice(0, x.length - 1); - } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - return x; -}; +var osName = _interopDefault(__webpack_require__(2)); + +function getUserAgent() { + try { + return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`; + } catch (error) { + if (/wmic os get Caption/.test(error.message)) { + return "Windows "; + } + + throw error; + } +} + +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map /***/ }), @@ -13268,6 +13505,9 @@ exports.default = async (body, headers) => { } if (body instanceof fs_1.ReadStream) { const { size } = await statAsync(body.path); + if (size === 0) { + return undefined; + } return size; } return undefined; @@ -13277,12 +13517,14 @@ exports.default = async (body, headers) => { /***/ }), /***/ 790: -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const tls_1 = __webpack_require__(16); +function isTLSSocket(socket) { + return socket.encrypted; +} const deferToConnect = (socket, fn) => { let listeners; if (typeof fn === 'function') { @@ -13299,7 +13541,7 @@ const deferToConnect = (socket, fn) => { if (hasConnectListener) { listeners.connect(); } - if (socket instanceof tls_1.TLSSocket && hasSecureConnectListener) { + if (isTLSSocket(socket) && hasSecureConnectListener) { if (socket.authorized) { listeners.secureConnect(); } @@ -13330,27 +13572,23 @@ module.exports.default = deferToConnect; /***/ }), /***/ 796: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, '__esModule', { value: true }); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var osName = _interopDefault(__webpack_require__(2)); - function getUserAgent() { - try { - return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`; - } catch (error) { - if (/wmic os get Caption/.test(error.message)) { - return "Windows "; - } - - return ""; + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; } + + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + + return ""; } exports.getUserAgent = getUserAgent; @@ -13365,6 +13603,7 @@ exports.getUserAgent = getUserAgent; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.TimeoutError = void 0; const net = __webpack_require__(631); const unhandle_1 = __webpack_require__(784); const reentry = Symbol('reentry'); @@ -13615,6 +13854,16 @@ module.exports = require("dns"); module.exports = require("url"); +/***/ }), + +/***/ 839: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); + + /***/ }), /***/ 842: @@ -27929,28 +28178,27 @@ function authenticationBeforeRequest(state, options) { /***/ }), /***/ 866: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(module) { -"use strict"; +module.exports = removeHook; -var shebangRegex = __webpack_require__(816); +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } -module.exports = function (str) { - var match = str.match(shebangRegex); + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - if (!match) { - return null; - } + if (index === -1) { + return; + } - var arr = match[0].replace(/#! ?/, '').split(' '); - var bin = arr[0].split('/').pop(); - var arg = arr[1]; - - return (bin === 'env' ? - arg : - bin + (arg ? ' ' + arg : '') - ); -}; + state.registry[name].splice(index, 1); +} /***/ }), @@ -29030,13 +29278,16 @@ Object.defineProperty(exports, '__esModule', { value: true }); var request = __webpack_require__(753); var universalUserAgent = __webpack_require__(796); -const VERSION = "4.5.1"; +const VERSION = "4.6.1"; class GraphqlError extends Error { constructor(request, response) { const message = response.data.errors[0].message; super(message); Object.assign(this, response.data); + Object.assign(this, { + headers: response.headers + }); this.name = "GraphqlError"; this.request = request; // Maintains proper stack trace (only available on V8) @@ -29050,13 +29301,26 @@ class GraphqlError extends Error { } const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; +const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; function graphql(request, query, options) { - options = typeof query === "string" ? options = Object.assign({ + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); + } + + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)); + } + } + + const parsedOptions = typeof query === "string" ? Object.assign({ query - }, options) : options = query; - const requestOptions = Object.keys(options).reduce((result, key) => { + }, options) : query; + const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = options[key]; + result[key] = parsedOptions[key]; return result; } @@ -29064,12 +29328,27 @@ function graphql(request, query, options) { result.variables = {}; } - result.variables[key] = options[key]; + result.variables[key] = parsedOptions[key]; return result; - }, {}); + }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix + // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 + + const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; + + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request(requestOptions).then(response => { if (response.data.errors) { + const headers = {}; + + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlError(requestOptions, { + headers, data: response.data }); } @@ -29125,6 +29404,7 @@ const QuickLRU = __webpack_require__(290); const kCurrentStreamsCount = Symbol('currentStreamsCount'); const kRequest = Symbol('request'); const kOriginSet = Symbol('cachedOriginSet'); +const kGracefullyClosing = Symbol('gracefullyClosing'); const nameKeys = [ // `http2.connect()` options @@ -29161,52 +29441,35 @@ const nameKeys = [ 'sessionIdContext' ]; -const removeSession = (where, name, session) => { - if (name in where) { - const index = where[name].indexOf(session); +const getSortedIndex = (array, value, compare) => { + let low = 0; + let high = array.length; - if (index !== -1) { - where[name].splice(index, 1); + while (low < high) { + const mid = (low + high) >>> 1; - if (where[name].length === 0) { - delete where[name]; - } - - return true; + /* istanbul ignore next */ + if (compare(array[mid], value)) { + // This never gets called because we use descending sort. Better to have this anyway. + low = mid + 1; + } else { + high = mid; } } - return false; + return low; }; -const addSession = (where, name, session) => { - if (name in where) { - where[name].push(session); - } else { - where[name] = [session]; - } -}; - -const getSessions = (where, name, normalizedOrigin) => { - if (!(name in where)) { - return []; - } - - return where[name].filter(session => { - return !session.closed && !session.destroyed && session[kOriginSet].includes(normalizedOrigin); - }); +const compareSessions = (a, b) => { + return a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; }; // See https://tools.ietf.org/html/rfc8336 -const closeCoveredSessions = (where, name, session) => { - if (!(name in where)) { - return; - } - +const closeCoveredSessions = (where, session) => { // Clients SHOULD NOT emit new requests on any connection whose Origin // Set is a proper subset of another connection's Origin Set, and they // SHOULD close it once all outstanding requests are satisfied. - for (const coveredSession of where[name]) { + for (const coveredSession of where) { if ( // The set is a proper subset when its length is less than the other set. coveredSession[kOriginSet].length < session[kOriginSet].length && @@ -29215,43 +29478,68 @@ const closeCoveredSessions = (where, name, session) => { coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && // Makes sure that the session can handle all requests from the covered session. - // TODO: can the session become uncovered when a stream is closed after checking this condition? coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams ) { // This allows pending requests to finish and prevents making new requests. - coveredSession.close(); + gracefullyClose(coveredSession); } } }; // This is basically inverted `closeCoveredSessions(...)`. -const closeSessionIfCovered = (where, name, coveredSession) => { - if (!(name in where)) { - return; - } - - for (const session of where[name]) { +const closeSessionIfCovered = (where, coveredSession) => { + for (const session of where) { if ( coveredSession[kOriginSet].length < session[kOriginSet].length && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams ) { - coveredSession.close(); + gracefullyClose(coveredSession); } } }; +const getSessions = ({agent, isFree}) => { + const result = {}; + + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in agent.sessions) { + const sessions = agent.sessions[normalizedOptions]; + + const filtered = sessions.filter(session => { + const result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + + return isFree ? result : !result; + }); + + if (filtered.length !== 0) { + result[normalizedOptions] = filtered; + } + } + + return result; +}; + +const gracefullyClose = session => { + session[kGracefullyClosing] = true; + + if (session[kCurrentStreamsCount] === 0) { + session.close(); + } +}; + class Agent extends EventEmitter { - constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 1, maxCachedTlsSessions = 100} = {}) { + constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) { super(); // A session is considered busy when its current streams count // is equal to or greater than the `maxConcurrentStreams` value. - this.busySessions = {}; // A session is considered free when its current streams count // is less than the `maxConcurrentStreams` value. - this.freeSessions = {}; + + // SESSIONS[NORMALIZED_OPTIONS] = []; + this.sessions = {}; // The queue for creating new sessions. It looks like this: // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION @@ -29265,14 +29553,16 @@ class Agent extends EventEmitter { // Each session will use this timeout value. this.timeout = timeout; - // Max sessions per origin. + // Max sessions in total this.maxSessions = maxSessions; - // Max free sessions per origin. + // Max free sessions in total // TODO: decreasing `maxFreeSessions` should close some sessions - // TODO: should `maxFreeSessions` be related only to sessions with 0 pending streams? this.maxFreeSessions = maxFreeSessions; + this._freeSessionsCount = 0; + this._sessionsCount = 0; + // We don't support push streams by default. this.settings = { enablePush: false @@ -29313,23 +29603,19 @@ class Agent extends EventEmitter { return; } - // We need the busy sessions length to check if a session can be created. - const busyLength = getSessions(this.busySessions, normalizedOptions, normalizedOrigin).length; const item = this.queue[normalizedOptions][normalizedOrigin]; // The entry function can be run only once. - if (busyLength < this.maxSessions && !item.completed) { + // BUG: The session may be never created when: + // - the first condition is false AND + // - this function is never called with the same arguments in the future. + if (this._sessionsCount < this.maxSessions && !item.completed) { item.completed = true; item(); } } - _closeCoveredSessions(normalizedOptions, session) { - closeCoveredSessions(this.freeSessions, normalizedOptions, session); - closeCoveredSessions(this.busySessions, normalizedOptions, session); - } - getSession(origin, options, listeners) { return new Promise((resolve, reject) => { if (Array.isArray(listeners)) { @@ -29353,28 +29639,65 @@ class Agent extends EventEmitter { return; } - if (normalizedOptions in this.freeSessions) { - // Look for all available free sessions. - const freeSessions = getSessions(this.freeSessions, normalizedOptions, normalizedOrigin); + if (normalizedOptions in this.sessions) { + const sessions = this.sessions[normalizedOptions]; - if (freeSessions.length !== 0) { - // Use session which has the biggest stream capacity in order to use the smallest number of sessions possible. - const session = freeSessions.reduce((previousSession, nextSession) => { - if ( - nextSession.remoteSettings.maxConcurrentStreams >= previousSession.remoteSettings.maxConcurrentStreams && - nextSession[kCurrentStreamsCount] > previousSession[kCurrentStreamsCount] - ) { - return nextSession; - } + let maxConcurrentStreams = -1; + let currentStreamsCount = -1; + let optimalSession; - return previousSession; - }); + // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. + // Additionally, we are looking for session which has biggest current pending streams count. + for (const session of sessions) { + const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; - for (const {resolve} of listeners) { - // TODO: The session can get busy here - resolve(session); + if (sessionMaxConcurrentStreams < maxConcurrentStreams) { + break; } + if (session[kOriginSet].includes(normalizedOrigin)) { + const sessionCurrentStreamsCount = session[kCurrentStreamsCount]; + + if ( + sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || + session[kGracefullyClosing] || + // Unfortunately the `close` event isn't called immediately, + // so `session.destroyed` is `true`, but `session.closed` is `false`. + session.destroyed + ) { + continue; + } + + // We only need set this once. + if (!optimalSession) { + maxConcurrentStreams = sessionMaxConcurrentStreams; + } + + // We're looking for the session which has biggest current pending stream count, + // in order to minimalize the amount of active sessions. + if (sessionCurrentStreamsCount > currentStreamsCount) { + optimalSession = session; + currentStreamsCount = sessionCurrentStreamsCount; + } + } + } + + if (optimalSession) { + /* istanbul ignore next: safety check */ + if (listeners.length !== 1) { + for (const {reject} of listeners) { + const error = new Error( + `Expected the length of listeners to be 1, got ${listeners.length}.\n` + + 'Please report this to https://github.com/szmarczak/http2-wrapper/' + ); + + reject(error); + } + + return; + } + + listeners[0].resolve(optimalSession); return; } } @@ -29384,6 +29707,9 @@ class Agent extends EventEmitter { // There's already an item in the queue, just attach ourselves to it. this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); + // This shouldn't be executed here. + // See the comment inside _tryToCreateNewSession. + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); return; } } else { @@ -29408,64 +29734,28 @@ class Agent extends EventEmitter { const entry = () => { const name = `${normalizedOrigin}:${normalizedOptions}`; let receivedSettings = false; - let servername; try { - const tlsSessionCache = this.tlsSessionCache.get(name); - const session = http2.connect(origin, { createConnection: this.createConnection, settings: this.settings, - session: tlsSessionCache ? tlsSessionCache.session : undefined, + session: this.tlsSessionCache.get(name), ...options }); session[kCurrentStreamsCount] = 0; - - // Tries to free the session. - const freeSession = () => { - // Fetch the smallest amount of free sessions of any origin we have. - const freeSessionsCount = session[kOriginSet].reduce((accumulator, origin) => { - return Math.min(accumulator, getSessions(this.freeSessions, normalizedOptions, origin).length); - }, Infinity); - - // Check the limit. - if (freeSessionsCount < this.maxFreeSessions) { - addSession(this.freeSessions, normalizedOptions, session); - - return true; - } - - return false; - }; + session[kGracefullyClosing] = false; const isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + let wasFree = true; session.socket.once('session', tlsSession => { - // We need to cache the servername due to a bug in OpenSSL. - setImmediate(() => { - this.tlsSessionCache.set(name, { - session: tlsSession, - servername - }); - }); - }); - - // OpenSSL bug workaround. - // See https://github.com/nodejs/node/issues/28985 - session.socket.once('secureConnect', () => { - servername = session.socket.servername; - - if (servername === false && typeof tlsSessionCache !== 'undefined' && typeof tlsSessionCache.servername !== 'undefined') { - session.socket.servername = tlsSessionCache.servername; - } + this.tlsSessionCache.set(name, tlsSession); }); session.once('error', error => { - // `receivedSettings` is true when the session has successfully connected. - if (!receivedSettings) { - for (const {reject} of listeners) { - reject(error); - } + // Listeners are empty when the session successfully connected. + for (const {reject} of listeners) { + reject(error); } // The connection got broken, purge the cache. @@ -29474,32 +29764,49 @@ class Agent extends EventEmitter { session.setTimeout(this.timeout, () => { // Terminates all streams owned by this session. + // TODO: Maybe the streams should have a "Session timed out" error? session.destroy(); }); session.once('close', () => { - if (!receivedSettings) { + if (receivedSettings) { + // 1. If it wasn't free then no need to decrease because + // it has been decreased already in session.request(). + // 2. `stream.once('close')` won't increment the count + // because the session is already closed. + if (wasFree) { + this._freeSessionsCount--; + } + + this._sessionsCount--; + + // This cannot be moved to the stream logic, + // because there may be a session that hadn't made a single request. + const where = this.sessions[normalizedOptions]; + where.splice(where.indexOf(session), 1); + + if (where.length === 0) { + delete this.sessions[normalizedOptions]; + } + } else { // Broken connection const error = new Error('Session closed without receiving a SETTINGS frame'); + error.code = 'HTTP2WRAPPER_NOSETTINGS'; for (const {reject} of listeners) { reject(error); } + + removeFromQueue(); } - removeFromQueue(); - - // This cannot be moved to the stream logic, - // because there may be a session that hadn't made a single request. - removeSession(this.freeSessions, normalizedOptions, session); - // There may be another session awaiting. this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); }); // Iterates over the queue and processes listeners. const processListeners = () => { - if (!(normalizedOptions in this.queue)) { + if (!(normalizedOptions in this.queue) || !isFree()) { return; } @@ -29514,10 +29821,11 @@ class Agent extends EventEmitter { listeners.shift().resolve(session); } - if (this.queue[normalizedOptions][origin].listeners.length === 0) { - delete this.queue[normalizedOptions][origin]; + const where = this.queue[normalizedOptions]; + if (where[origin].listeners.length === 0) { + delete where[origin]; - if (Object.keys(this.queue[normalizedOptions]).length === 0) { + if (Object.keys(where).length === 0) { delete this.queue[normalizedOptions]; break; } @@ -29532,7 +29840,7 @@ class Agent extends EventEmitter { }; // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. - session.once('origin', () => { + session.on('origin', () => { session[kOriginSet] = session.originSet; if (!isFree()) { @@ -29540,18 +29848,19 @@ class Agent extends EventEmitter { return; } - // Close covered sessions (if possible). - this._closeCoveredSessions(normalizedOptions, session); - processListeners(); - // `session.remoteSettings.maxConcurrentStreams` might get increased - session.on('remoteSettings', () => { - this._closeCoveredSessions(normalizedOptions, session); - }); + // Close covered sessions (if possible). + closeCoveredSessions(this.sessions[normalizedOptions], session); }); session.once('remoteSettings', () => { + // Fix Node.js bug preventing the process from exiting + session.ref(); + session.unref(); + + this._sessionsCount++; + // The Agent could have been destroyed already. if (entry.destroyed) { const error = new Error('Agent has been destroyed'); @@ -29565,25 +29874,31 @@ class Agent extends EventEmitter { } session[kOriginSet] = session.originSet; - this.emit('session', session); - if (freeSession()) { - // Process listeners, we're free. - processListeners(); - } else if (this.maxFreeSessions === 0) { - processListeners(); + { + const where = this.sessions; - // We're closing ASAP, when all possible requests have been made for this event loop tick. - setImmediate(() => { - session.close(); - }); - } else { - // Too late, another free session took these listeners. - session.close(); + if (normalizedOptions in where) { + const sessions = where[normalizedOptions]; + sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); + } else { + where[normalizedOptions] = [session]; + } } + this._freeSessionsCount += 1; + receivedSettings = true; + + this.emit('session', session); + + processListeners(); removeFromQueue(); + // TODO: Close last recently used (or least used?) session + if (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) { + session.close(); + } + // Check if we haven't managed to execute all listeners. if (listeners.length !== 0) { // Request for a new session with predefined listeners. @@ -29591,64 +29906,68 @@ class Agent extends EventEmitter { listeners.length = 0; } - receivedSettings = true; - // `session.remoteSettings.maxConcurrentStreams` might get increased session.on('remoteSettings', () => { - // Check if we're eligible to become a free session - if (isFree() && removeSession(this.busySessions, normalizedOptions, session)) { - // Check for free seats - if (freeSession()) { - processListeners(); - } else { - // Assume it's still a busy session - addSession(this.busySessions, normalizedOptions, session); - } - } + processListeners(); + + // In case the Origin Set changes + closeCoveredSessions(this.sessions[normalizedOptions], session); }); }); // Shim `session.request()` in order to catch all streams session[kRequest] = session.request; - session.request = headers => { - const stream = session[kRequest](headers, { - endStream: false - }); + session.request = (headers, streamOptions) => { + if (session[kGracefullyClosing]) { + throw new Error('The session is gracefully closing. No new streams are allowed.'); + } - // The process won't exit until the session is closed. + const stream = session[kRequest](headers, streamOptions); + + // The process won't exit until the session is closed or all requests are gone. session.ref(); ++session[kCurrentStreamsCount]; - // Check if we became busy - if (!isFree() && removeSession(this.freeSessions, normalizedOptions, session)) { - addSession(this.busySessions, normalizedOptions, session); + if (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) { + this._freeSessionsCount--; } stream.once('close', () => { + wasFree = isFree(); + --session[kCurrentStreamsCount]; - if (isFree()) { - if (session[kCurrentStreamsCount] === 0) { - // All requests are finished, the process may exit now. - session.unref(); - } + if (!session.destroyed && !session.closed) { + closeSessionIfCovered(this.sessions[normalizedOptions], session); - // Check if we are no longer busy and the session is not broken. - if (removeSession(this.busySessions, normalizedOptions, session) && !session.destroyed && !session.closed) { - // Check the sessions count of this authority and compare it to `maxSessionsCount`. - if (freeSession()) { - this._closeCoveredSessions(normalizedOptions, session); - processListeners(); - } else { + if (isFree() && !session.closed) { + if (!wasFree) { + this._freeSessionsCount++; + + wasFree = true; + } + + const isEmpty = session[kCurrentStreamsCount] === 0; + + if (isEmpty) { + session.unref(); + } + + if ( + isEmpty && + ( + this._freeSessionsCount > this.maxFreeSessions || + session[kGracefullyClosing] + ) + ) { session.close(); + } else { + closeCoveredSessions(this.sessions[normalizedOptions], session); + processListeners(); } } } - - if (!session.destroyed && !session.closed) { - closeSessionIfCovered(this.freeSessions, normalizedOptions, session); - } }); return stream; @@ -29671,12 +29990,16 @@ class Agent extends EventEmitter { }); } - request(origin, options, headers) { + request(origin, options, headers, streamOptions) { return new Promise((resolve, reject) => { this.getSession(origin, options, [{ reject, resolve: session => { - resolve(session.request(headers)); + try { + resolve(session.request(headers, streamOptions)); + } catch (error) { + reject(error); + } } }]); }); @@ -29700,8 +30023,8 @@ class Agent extends EventEmitter { } closeFreeSessions() { - for (const freeSessions of Object.values(this.freeSessions)) { - for (const session of freeSessions) { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { if (session[kCurrentStreamsCount] === 0) { session.close(); } @@ -29710,14 +30033,8 @@ class Agent extends EventEmitter { } destroy(reason) { - for (const busySessions of Object.values(this.busySessions)) { - for (const session of busySessions) { - session.destroy(reason); - } - } - - for (const freeSessions of Object.values(this.freeSessions)) { - for (const session of freeSessions) { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { session.destroy(reason); } } @@ -29731,8 +30048,19 @@ class Agent extends EventEmitter { // New requests should NOT attach to destroyed sessions this.queue = {}; } + + get freeSessions() { + return getSessions({agent: this, isFree: true}); + } + + get busySessions() { + return getSessions({agent: this, isFree: false}); + } } +Agent.kCurrentStreamsCount = kCurrentStreamsCount; +Agent.kGracefullyClosing = kGracefullyClosing; + module.exports = { Agent, globalAgent: new Agent() @@ -29746,8 +30074,18 @@ module.exports = { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; Object.defineProperty(exports, "__esModule", { value: true }); -const p_cancelable_1 = __webpack_require__(557); +exports.defaultHandler = void 0; const is_1 = __webpack_require__(534); const as_promise_1 = __webpack_require__(952); const create_rejection_1 = __webpack_require__(910); @@ -29761,12 +30099,23 @@ const errors = { MaxRedirectsError: as_promise_1.MaxRedirectsError, TimeoutError: as_promise_1.TimeoutError, ParseError: as_promise_1.ParseError, - CancelError: p_cancelable_1.CancelError, + CancelError: as_promise_1.CancelError, UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError, UploadError: as_promise_1.UploadError }; -const { normalizeArguments, mergeOptions } = as_promise_1.PromisableRequest; -const getPromiseOrStream = (options) => options.isStream ? new core_1.default(options.url, options) : as_promise_1.default(options); +// The `delay` package weighs 10KB (!) +const delay = async (ms) => new Promise(resolve => { + setTimeout(resolve, ms); +}); +const { normalizeArguments } = core_1.default; +const mergeOptions = (...sources) => { + let mergedOptions; + for (const source of sources) { + mergedOptions = normalizeArguments(undefined, source, mergedOptions); + } + return mergedOptions; +}; +const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options); const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults); const aliases = [ 'get', @@ -29808,17 +30157,20 @@ const create = (defaults) => { return result; })); // Got interface - const got = ((url, options) => { + const got = ((url, options = {}, _defaults) => { var _a, _b; let iteration = 0; const iterateHandlers = (newOptions) => { return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); }; + // TODO: Remove this in Got 12. if (is_1.default.plainObject(url)) { - options = { + const mergedOptions = { ...url, ...options }; + core_1.setNonEnumerableProperties([url, options], mergedOptions); + options = mergedOptions; url = undefined; } try { @@ -29826,13 +30178,13 @@ const create = (defaults) => { let initHookError; try { callInitHooks(defaults.options.hooks.init, options); - callInitHooks((_a = options === null || options === void 0 ? void 0 : options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); + callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); } catch (error) { initHookError = error; } // Normalize options & call handlers - const normalizedOptions = normalizeArguments(url, options, defaults.options); + const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options); normalizedOptions[core_1.kIsNormalizedAlready] = true; if (initHookError) { throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions); @@ -29840,11 +30192,11 @@ const create = (defaults) => { return iterateHandlers(normalizedOptions); } catch (error) { - if (options === null || options === void 0 ? void 0 : options.isStream) { + if (options.isStream) { throw error; } else { - return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options === null || options === void 0 ? void 0 : options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); + return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); } } }); @@ -29878,6 +30230,9 @@ const create = (defaults) => { }; // Pagination const paginateEach = (async function* (url, options) { + // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4. + // Error: Argument of type 'Merge> | undefined' is not assignable to parameter of type 'Options | undefined'. + // @ts-expect-error let normalizedOptions = normalizeArguments(url, options, defaults.options); normalizedOptions.resolveBodyOnly = false; const pagination = normalizedOptions.pagination; @@ -29888,9 +30243,14 @@ const create = (defaults) => { let { countLimit } = pagination; let numberOfRequests = 0; while (numberOfRequests < pagination.requestLimit) { + if (numberOfRequests !== 0) { + // eslint-disable-next-line no-await-in-loop + await delay(pagination.backoff); + } + // @ts-expect-error FIXME! // TODO: Throw when result is not an instance of Response // eslint-disable-next-line no-await-in-loop - const result = (await got('', normalizedOptions)); + const result = (await got(undefined, undefined, normalizedOptions)); // eslint-disable-next-line no-await-in-loop const parsed = await pagination.transform(result); const current = []; @@ -29922,12 +30282,10 @@ const create = (defaults) => { numberOfRequests++; } }); - got.paginate = ((url, options) => { - return paginateEach(url, options); - }); + got.paginate = paginateEach; got.paginate.all = (async (url, options) => { const results = []; - for await (const item of got.paginate(url, options)) { + for await (const item of paginateEach(url, options)) { results.push(item); } return results; @@ -29943,16 +30301,18 @@ const create = (defaults) => { return got(url, { ...options, method, isStream: true }); }); } - Object.assign(got, { ...errors, mergeOptions }); + Object.assign(got, errors); Object.defineProperty(got, 'defaults', { value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), writable: defaults.mutableDefaults, configurable: defaults.mutableDefaults, enumerable: true }); + got.mergeOptions = mergeOptions; return got; }; exports.default = create; +__exportStar(__webpack_require__(839), exports); /***/ }), @@ -30064,7 +30424,7 @@ exports.default = createRejection; Object.defineProperty(exports, '__esModule', { value: true }); -const VERSION = "1.0.0"; +const VERSION = "1.0.3"; /** * @param octokit Octokit instance @@ -30092,52 +30452,6 @@ exports.requestLog = requestLog; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 927: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const types_1 = __webpack_require__(36); -const retryAfterStatusCodes = new Set([413, 429, 503]); -const isErrorWithResponse = (error) => (error instanceof types_1.HTTPError || error instanceof types_1.ParseError || error instanceof types_1.MaxRedirectsError); -const calculateRetryDelay = ({ attemptCount, retryOptions, error }) => { - if (attemptCount > retryOptions.limit) { - return 0; - } - const hasMethod = retryOptions.methods.includes(error.options.method); - const hasErrorCode = retryOptions.errorCodes.includes(error.code); - const hasStatusCode = isErrorWithResponse(error) && retryOptions.statusCodes.includes(error.response.statusCode); - if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { - return 0; - } - if (isErrorWithResponse(error)) { - const { response } = error; - if (response && 'retry-after' in response.headers && retryAfterStatusCodes.has(response.statusCode)) { - let after = Number(response.headers['retry-after']); - if (Number.isNaN(after)) { - after = Date.parse(response.headers['retry-after']) - Date.now(); - } - else { - after *= 1000; - } - if (retryOptions.maxRetryAfter === undefined || after > retryOptions.maxRetryAfter) { - return 0; - } - return after; - } - if (response.statusCode === 413) { - return 0; - } - } - const noise = Math.random() * 100; - return ((2 ** (attemptCount - 1)) * 1000) + noise; -}; -exports.default = calculateRetryDelay; - - /***/ }), /***/ 929: @@ -30162,6 +30476,7 @@ function hasNextPage (link) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0; const util_1 = __webpack_require__(669); const stream_1 = __webpack_require__(413); const fs_1 = __webpack_require__(747); @@ -30173,10 +30488,9 @@ const http_timer_1 = __webpack_require__(490); const cacheable_lookup_1 = __webpack_require__(570); const CacheableRequest = __webpack_require__(390); const decompressResponse = __webpack_require__(861); -// @ts-ignore Missing types +// @ts-expect-error Missing types const http2wrapper = __webpack_require__(157); const lowercaseKeys = __webpack_require__(474); -const getStream = __webpack_require__(145); const is_1 = __webpack_require__(534); const get_body_size_1 = __webpack_require__(786); const is_form_data_1 = __webpack_require__(460); @@ -30185,8 +30499,13 @@ const timed_out_1 = __webpack_require__(811); const url_to_options_1 = __webpack_require__(10); const options_to_url_1 = __webpack_require__(907); const weakable_map_1 = __webpack_require__(48); +const get_buffer_1 = __webpack_require__(284); const dns_ip_version_1 = __webpack_require__(738); +const is_response_ok_1 = __webpack_require__(422); const deprecation_warning_1 = __webpack_require__(189); +const normalize_arguments_1 = __webpack_require__(992); +const calculate_retry_delay_1 = __webpack_require__(594); +let globalDnsCache; const kRequest = Symbol('request'); const kResponse = Symbol('response'); const kResponseSize = Symbol('responseSize'); @@ -30203,15 +30522,24 @@ const kTriggerRead = Symbol('triggerRead'); const kBody = Symbol('body'); const kJobs = Symbol('jobs'); const kOriginalResponse = Symbol('originalResponse'); +const kRetryTimeout = Symbol('retryTimeout'); exports.kIsNormalizedAlready = Symbol('isNormalizedAlready'); const supportsBrotli = is_1.default.string(process.versions.brotli); exports.withoutBody = new Set(['GET', 'HEAD']); -exports.knownHookEvents = ['init', 'beforeRequest', 'beforeRedirect', 'beforeError']; +exports.knownHookEvents = [ + 'init', + 'beforeRequest', + 'beforeRedirect', + 'beforeError', + 'beforeRetry', + // Promise-Only + 'afterResponse' +]; function validateSearchParameters(searchParameters) { // eslint-disable-next-line guard-for-in for (const key in searchParameters) { const value = searchParameters[key]; - if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value)) { + if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) { throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); } } @@ -30224,6 +30552,7 @@ const waitForOpenFile = async (file) => new Promise((resolve, reject) => { const onError = (error) => { reject(error); }; + // Node.js 12 has incomplete types if (!file.pending) { resolve(); } @@ -30240,7 +30569,7 @@ const nonEnumerableProperties = [ 'json', 'form' ]; -const setNonEnumerableProperties = (sources, to) => { +exports.setNonEnumerableProperties = (sources, to) => { // Non enumerable properties shall not be merged const properties = {}; for (const source of sources) { @@ -30255,13 +30584,17 @@ const setNonEnumerableProperties = (sources, to) => { writable: true, configurable: true, enumerable: false, - // @ts-ignore TS doesn't see the check above + // @ts-expect-error TS doesn't see the check above value: source[name] }; } } Object.defineProperties(to, properties); }; +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ class RequestError extends Error { constructor(message, error, self) { var _a; @@ -30295,7 +30628,7 @@ class RequestError extends Error { } this.timings = (_a = this.request) === null || _a === void 0 ? void 0 : _a.timings; // Recover the original stacktrace - if (!is_1.default.undefined(error.stack)) { + if (is_1.default.string(error.stack) && is_1.default.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(); @@ -30308,6 +30641,10 @@ class RequestError extends Error { } } exports.RequestError = RequestError; +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ class MaxRedirectsError extends RequestError { constructor(request) { super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); @@ -30315,6 +30652,10 @@ class MaxRedirectsError extends RequestError { } } exports.MaxRedirectsError = MaxRedirectsError; +/** +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. +*/ class HTTPError extends RequestError { constructor(response) { super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); @@ -30322,6 +30663,10 @@ class HTTPError extends RequestError { } } exports.HTTPError = HTTPError; +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ class CacheError extends RequestError { constructor(error, request) { super(error.message, error, request); @@ -30329,6 +30674,9 @@ class CacheError extends RequestError { } } exports.CacheError = CacheError; +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ class UploadError extends RequestError { constructor(error, request) { super(error.message, error, request); @@ -30336,6 +30684,10 @@ class UploadError extends RequestError { } } exports.UploadError = UploadError; +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ class TimeoutError extends RequestError { constructor(error, timings, request) { super(error.message, error, request); @@ -30345,6 +30697,9 @@ class TimeoutError extends RequestError { } } exports.TimeoutError = TimeoutError; +/** +An error to be thrown when reading from response stream fails. +*/ class ReadError extends RequestError { constructor(error, request) { super(error.message, error, request); @@ -30352,6 +30707,9 @@ class ReadError extends RequestError { } } exports.ReadError = ReadError; +/** +An error to be thrown when given an unsupported protocol. +*/ class UnsupportedProtocolError extends RequestError { constructor(options) { super(`Unsupported protocol "${options.url.protocol}"`, {}, options); @@ -30370,6 +30728,9 @@ const proxiedRequestEvents = [ class Request extends stream_1.Duplex { constructor(url, options = {}, defaults) { super({ + // This must be false, to enable throwing after destroy + // It is used for retry logic in Promise API + autoDestroy: false, // It needs to be zero because we're just proxying the data to another stream highWaterMark: 0 }); @@ -30381,6 +30742,7 @@ class Request extends stream_1.Duplex { this[kStopReading] = false; this[kTriggerRead] = false; this[kJobs] = []; + this.retryCount = 0; // TODO: Remove this when targeting Node.js >= 12 this._progressCallbacks = []; const unlockWrite = () => this._unlockWrite(); @@ -30409,18 +30771,28 @@ class Request extends stream_1.Duplex { if (json || body || form) { this._lockWrite(); } - (async (nonNormalizedOptions) => { + if (exports.kIsNormalizedAlready in options) { + this.options = options; + } + else { + try { + // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible + this.options = this.constructor.normalizeArguments(url, options, defaults); + } + catch (error) { + // TODO: Move this to `_destroy()` + if (is_1.default.nodeStream(options.body)) { + options.body.destroy(); + } + this.destroy(error); + return; + } + } + (async () => { var _a; try { - if (nonNormalizedOptions.body instanceof fs_1.ReadStream) { - await waitForOpenFile(nonNormalizedOptions.body); - } - if (exports.kIsNormalizedAlready in nonNormalizedOptions) { - this.options = nonNormalizedOptions; - } - else { - // @ts-ignore Common TypeScript bug saying that `this.constructor` is not accessible - this.options = this.constructor.normalizeArguments(url, nonNormalizedOptions, defaults); + if (this.options.body instanceof fs_1.ReadStream) { + await waitForOpenFile(this.options.body); } const { url: normalizedURL } = this.options; if (!normalizedURL) { @@ -30438,6 +30810,8 @@ class Request extends stream_1.Duplex { for (const job of this[kJobs]) { job(); } + // Prevent memory leak + this[kJobs].length = 0; this.requestInitialized = true; } catch (error) { @@ -30450,20 +30824,20 @@ class Request extends stream_1.Duplex { this.destroy(error); } } - })(options); + })(); } static normalizeArguments(url, options, defaults) { - var _a, _b, _c, _d; + var _a, _b, _c, _d, _e; const rawOptions = options; if (is_1.default.object(url) && !is_1.default.urlInstance(url)) { options = { ...defaults, ...url, ...options }; } else { - if (url && options && options.url) { + if (url && options && options.url !== undefined) { throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); } options = { ...defaults, ...options }; - if (url) { + if (url !== undefined) { options.url = url; } if (is_1.default.urlInstance(options.url)) { @@ -30506,7 +30880,9 @@ class Request extends stream_1.Duplex { is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key); is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate); is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase); + is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx); } + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions); // `options.method` if (is_1.default.string(options.method)) { options.method = options.method.toUpperCase(); @@ -30532,10 +30908,24 @@ class Request extends stream_1.Duplex { // `options.searchParams` if ('searchParams' in options) { if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) { - if (!is_1.default.string(options.searchParams) && !(options.searchParams instanceof url_1.URLSearchParams)) { - validateSearchParameters(options.searchParams); + let searchParameters; + if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) { + searchParameters = new url_1.URLSearchParams(options.searchParams); + } + else { + validateSearchParameters(options.searchParams); + searchParameters = new url_1.URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in options.searchParams) { + const value = options.searchParams[key]; + if (value === null) { + searchParameters.append(key, ''); + } + else if (value !== undefined) { + searchParameters.append(key, value); + } + } } - const searchParameters = new url_1.URLSearchParams(options.searchParams); // `normalizeArguments()` is also used to merge options (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => { // Only use default if one isn't already defined @@ -30550,15 +30940,15 @@ class Request extends stream_1.Duplex { options.username = (_b = options.username) !== null && _b !== void 0 ? _b : ''; options.password = (_c = options.password) !== null && _c !== void 0 ? _c : ''; // `options.prefixUrl` & `options.url` - if (options.prefixUrl) { + if (is_1.default.undefined(options.prefixUrl)) { + options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : ''; + } + else { options.prefixUrl = options.prefixUrl.toString(); if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) { options.prefixUrl += '/'; } } - else { - options.prefixUrl = ''; - } if (is_1.default.string(options.url)) { if (options.url.startsWith('/')) { throw new Error('`input` must not start with a slash when using `prefixUrl`'); @@ -30569,6 +30959,9 @@ class Request extends stream_1.Duplex { options.url = options_to_url_1.default(options.prefixUrl, options); } if (options.url) { + if ('port' in options) { + delete options.port; + } // Make it possible to change `options.prefixUrl` let { prefixUrl } = options; Object.defineProperty(options, 'prefixUrl', { @@ -30590,6 +30983,7 @@ class Request extends stream_1.Duplex { } // Set search params if (options.searchParams) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string options.url.search = options.searchParams.toString(); } // Protocol check @@ -30623,7 +31017,7 @@ class Request extends stream_1.Duplex { getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); options.cookieJar = { setCookie, - getCookieString + getCookieString: getCookieString }; } } @@ -30631,12 +31025,47 @@ class Request extends stream_1.Duplex { const { cache } = options; if (cache) { if (!cacheableStore.has(cache)) { - cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => requestOptions[kRequest](requestOptions, handler)), cache)); + cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => { + const result = requestOptions[kRequest](requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (is_1.default.promise(result)) { + // @ts-expect-error + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + result.once = (event, handler) => { + if (event === 'error') { + result.catch(handler); + } + else if (event === 'abort') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once('abort', handler); + } + catch (_a) { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache)); } } + // `options.cacheOptions` + options.cacheOptions = { ...options.cacheOptions }; // `options.dnsCache` if (options.dnsCache === true) { - options.dnsCache = new cacheable_lookup_1.default(); + if (!globalDnsCache) { + globalDnsCache = new cacheable_lookup_1.default(); + } + options.dnsCache = globalDnsCache; } else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) { throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`); @@ -30678,7 +31107,7 @@ class Request extends stream_1.Duplex { if (defaults && !areHooksDefault) { for (const event of exports.knownHookEvents) { const defaultHooks = defaults.hooks[event]; - if (defaultHooks.length !== 0) { + if (defaultHooks.length > 0) { // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 options.hooks[event] = [ ...defaults.hooks[event], @@ -30713,6 +31142,9 @@ class Request extends stream_1.Duplex { if ('passphrase' in options) { deprecation_warning_1.default('"options.passphrase" was never documented, please use "options.https.passphrase"'); } + if ('pfx' in options) { + deprecation_warning_1.default('"options.pfx" was never documented, please use "options.https.pfx"'); + } // Other options if ('followRedirects' in options) { throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); @@ -30724,10 +31156,10 @@ class Request extends stream_1.Duplex { } } } - options.maxRedirects = (_d = options.maxRedirects) !== null && _d !== void 0 ? _d : 0; + options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0; // Set non-enumerable properties - setNonEnumerableProperties([defaults, rawOptions], options); - return options; + exports.setNonEnumerableProperties([defaults, rawOptions], options); + return normalize_arguments_1.default(options, defaults); } _lockWrite() { const onLockedWrite = () => { @@ -30813,7 +31245,7 @@ class Request extends stream_1.Duplex { } this[kBodySize] = Number(headers['content-length']) || undefined; } - async _onResponse(response) { + async _onResponseBase(response) { const { options } = this; const { url } = options; this[kOriginalResponse] = response; @@ -30829,6 +31261,7 @@ class Request extends stream_1.Duplex { typedResponse.request = this; typedResponse.isFromCache = response.fromCache || false; typedResponse.ip = this.ip; + typedResponse.retryCount = this.retryCount; this[kIsFromCache] = typedResponse.isFromCache; this[kResponseSize] = Number(response.headers['content-length']) || undefined; this[kResponse] = response; @@ -30845,7 +31278,8 @@ class Request extends stream_1.Duplex { response.once('aborted', () => { this._beforeError(new ReadError({ name: 'Error', - message: 'The server aborted the pending request' + message: 'The server aborted pending request', + code: 'ECONNRESET' }, this)); }); this.emit('downloadProgress', this.downloadProgress); @@ -30865,7 +31299,7 @@ class Request extends stream_1.Duplex { } if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { // We're being redirected, we don't care about the response. - // It'd be besto to abort the request, but we can't because + // It'd be best to abort the request, but we can't because // we would have to sacrifice the TCP connection. We don't want that. response.resume(); if (this[kRequest]) { @@ -30888,6 +31322,8 @@ class Request extends stream_1.Duplex { if ('form' in options) { delete options.form; } + this[kBody] = undefined; + delete options.headers['content-length']; } if (this.redirects.length >= options.maxRedirects) { this._beforeError(new MaxRedirectsError(this)); @@ -30901,7 +31337,7 @@ class Request extends stream_1.Duplex { const redirectString = redirectUrl.toString(); decodeURI(redirectString); // Redirecting to a different site, clear sensitive data. - if (redirectUrl.hostname !== url.hostname) { + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { if ('host' in options.headers) { delete options.headers.host; } @@ -30912,10 +31348,14 @@ class Request extends stream_1.Duplex { delete options.headers.authorization; } if (options.username || options.password) { - delete options.username; - delete options.password; + options.username = ''; + options.password = ''; } } + else { + redirectUrl.username = options.username; + redirectUrl.password = options.password; + } this.redirects.push(redirectString); options.url = redirectUrl; for (const hook of options.hooks.beforeRedirect) { @@ -30931,13 +31371,9 @@ class Request extends stream_1.Duplex { } return; } - const limitStatusCode = options.followRedirect ? 299 : 399; - const isOk = (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; - if (options.throwHttpErrors && !isOk) { - await this._beforeError(new HTTPError(typedResponse)); - if (this.destroyed) { - return; - } + if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) { + this._beforeError(new HTTPError(typedResponse)); + return; } response.on('readable', () => { if (this[kTriggerRead]) { @@ -30969,6 +31405,15 @@ class Request extends stream_1.Duplex { destination.statusCode = statusCode; } } + async _onResponse(response) { + try { + await this._onResponseBase(response); + } + catch (error) { + /* istanbul ignore next: better safe than sorry */ + this._beforeError(error); + } + } _onRequest(request) { const { options } = this; const { timeout, url } = options; @@ -30976,17 +31421,15 @@ class Request extends stream_1.Duplex { this[kCancelTimeouts] = timed_out_1.default(request, timeout, url); const responseEventName = options.cache ? 'cacheableResponse' : 'response'; request.once(responseEventName, (response) => { - this._onResponse(response); + void this._onResponse(response); }); request.once('error', (error) => { + var _a; // Force clean-up, because some packages (e.g. nock) don't do this. request.destroy(); - if (error instanceof timed_out_1.TimeoutError) { - error = new TimeoutError(error, this.timings, this); - } - else { - error = new RequestError(error.message, error, this); - } + // Node.js <= 12.18.2 mistakenly emits the response `end` first. + (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end'); + error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); this._beforeError(error); }); this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents); @@ -31000,14 +31443,11 @@ class Request extends stream_1.Duplex { body.once('error', (error) => { this._beforeError(new UploadError(error, this)); }); - body.once('end', () => { - delete options.body; - }); } else { this._unlockWrite(); if (!is_1.default.undefined(body)) { - this._writeRequest(body, null, () => { }); + this._writeRequest(body, undefined, () => { }); currentRequest.end(); this._lockWrite(); } @@ -31023,26 +31463,30 @@ class Request extends stream_1.Duplex { // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed Object.assign(options, url_to_options_1.default(url)); // `http-cache-semantics` checks this + // TODO: Fix this ignore. + // @ts-expect-error delete options.url; + let request; // This is ugly - const cacheRequest = cacheableStore.get(options.cache)(options, response => { - const typedResponse = response; - const { req } = typedResponse; + const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { // TODO: Fix `cacheable-response` - typedResponse._readableState.autoDestroy = false; - if (req) { - req.emit('cacheableResponse', typedResponse); + response._readableState.autoDestroy = false; + if (request) { + (await request).emit('cacheableResponse', response); } - resolve(typedResponse); + resolve(response); }); // Restore options options.url = url; cacheRequest.once('error', reject); - cacheRequest.once('request', resolve); + cacheRequest.once('request', async (requestOrPromise) => { + request = requestOrPromise; + resolve(request); + }); }); } async _makeRequest() { - var _a; + var _a, _b, _c, _d, _e; const { options } = this; const { headers } = options; for (const key in headers) { @@ -31068,11 +31512,14 @@ class Request extends stream_1.Duplex { // eslint-disable-next-line no-await-in-loop const result = await hook(options); if (!is_1.default.undefined(result)) { - // @ts-ignore Skip the type mismatch to support abstract responses + // @ts-expect-error Skip the type mismatch to support abstract responses options.request = () => result; break; } } + if (options.body && this[kBody] !== options.body) { + this[kBody] = options.body; + } const { agent, request, timeout, url } = options; if (options.dnsCache && !('lookup' in options)) { options.lookup = options.dnsCache.lookup; @@ -31108,14 +31555,20 @@ class Request extends stream_1.Duplex { // Prepare plain HTTP request options options[kRequest] = realFn; delete options.request; + // TODO: Fix this ignore. + // @ts-expect-error delete options.timeout; const requestOptions = options; + requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared; + requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic; + requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive; + requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult; // If `dnsLookupIpVersion` is not present do not override `family` if (options.dnsLookupIpVersion !== undefined) { try { requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion); } - catch (_b) { + catch (_f) { throw new Error('Invalid `dnsLookupIpVersion` option value'); } } @@ -31139,6 +31592,9 @@ class Request extends stream_1.Duplex { if (options.https.passphrase) { requestOptions.passphrase = options.https.passphrase; } + if (options.https.pfx) { + requestOptions.pfx = options.https.pfx; + } } try { let requestOrResponse = await fn(url, requestOptions); @@ -31149,20 +31605,45 @@ class Request extends stream_1.Duplex { options.request = request; options.timeout = timeout; options.agent = agent; + // HTTPS options restore + if (options.https) { + if ('rejectUnauthorized' in options.https) { + delete requestOptions.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + // @ts-expect-error - This one will be removed when we remove the alias. + delete requestOptions.checkServerIdentity; + } + if (options.https.certificateAuthority) { + delete requestOptions.ca; + } + if (options.https.certificate) { + delete requestOptions.cert; + } + if (options.https.key) { + delete requestOptions.key; + } + if (options.https.passphrase) { + delete requestOptions.passphrase; + } + if (options.https.pfx) { + delete requestOptions.pfx; + } + } if (isClientRequest(requestOrResponse)) { this._onRequest(requestOrResponse); // Emit the response after the stream has been ended } else if (this.writable) { this.once('finish', () => { - this._onResponse(requestOrResponse); + void this._onResponse(requestOrResponse); }); this._unlockWrite(); this.end(); this._lockWrite(); } else { - this._onResponse(requestOrResponse); + void this._onResponse(requestOrResponse); } } catch (error) { @@ -31172,23 +31653,7 @@ class Request extends stream_1.Duplex { throw new RequestError(error.message, error, this); } } - async _beforeError(error) { - if (this.destroyed) { - return; - } - this[kStopReading] = true; - if (!(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); - } - try { - const { response } = error; - if (response) { - response.setEncoding(this._readableState.encoding); - response.rawBody = await getStream.buffer(response); - response.body = response.rawBody.toString(); - } - } - catch (_) { } + async _error(error) { try { for (const hook of this.options.hooks.beforeError) { // eslint-disable-next-line no-await-in-loop @@ -31200,6 +31665,87 @@ class Request extends stream_1.Duplex { } this.destroy(error); } + _beforeError(error) { + if (this[kStopReading]) { + return; + } + const { options } = this; + const retryCount = this.retryCount + 1; + this[kStopReading] = true; + if (!(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + const typedError = error; + const { response } = typedError; + void (async () => { + if (response && !response.body) { + response.setEncoding(this._readableState.encoding); + try { + response.rawBody = await get_buffer_1.default(response); + response.body = response.rawBody.toString(); + } + catch (_a) { } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + backoff = await options.retry.calculateDelay({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: calculate_retry_delay_1.default({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: 0 + }) + }); + } + catch (error_) { + void this._error(new RequestError(error_.message, error_, this)); + return; + } + if (backoff) { + const retry = async () => { + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(this.options, typedError, retryCount); + } + } + catch (error_) { + void this._error(new RequestError(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', retryCount, error); + }; + this[kRetryTimeout] = setTimeout(retry, backoff); + return; + } + } + void this._error(typedError); + })(); + } _read() { this[kTriggerRead] = true; const response = this[kResponse]; @@ -31221,6 +31767,7 @@ class Request extends stream_1.Duplex { } } } + // Node.js 12 has incorrect types, so the encoding must be a string _write(chunk, encoding, callback) { const write = () => { this._writeRequest(chunk, encoding, callback); @@ -31233,6 +31780,10 @@ class Request extends stream_1.Duplex { } } _writeRequest(chunk, encoding, callback) { + if (this[kRequest].destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } this._progressCallbacks.push(() => { this[kUploadedSize] += Buffer.byteLength(chunk, encoding); const progress = this.uploadProgress; @@ -31242,7 +31793,7 @@ class Request extends stream_1.Duplex { }); // TODO: What happens if it's from cache? Then this[kRequest] won't be defined. this[kRequest].write(chunk, encoding, (error) => { - if (!error && this._progressCallbacks.length !== 0) { + if (!error && this._progressCallbacks.length > 0) { this._progressCallbacks.shift()(); } callback(error); @@ -31282,6 +31833,9 @@ class Request extends stream_1.Duplex { } _destroy(error, callback) { var _a; + this[kStopReading] = true; + // Prevent further retries + clearTimeout(this[kRetryTimeout]); if (kRequest in this) { this[kCancelTimeouts](); // TODO: Remove the next `if` when these get fixed: @@ -31295,18 +31849,30 @@ class Request extends stream_1.Duplex { } callback(error); } + get _isAboutToError() { + return this[kStopReading]; + } + /** + The remote IP address. + */ get ip() { var _a; - return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket.remoteAddress; + return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress; } + /** + Indicates whether the request has been aborted or not. + */ get aborted() { var _a, _b, _c; return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete); } get socket() { - var _a; - return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket; + var _a, _b; + return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined; } + /** + Progress event for downloading (receiving a response). + */ get downloadProgress() { let percent; if (this[kResponseSize]) { @@ -31324,6 +31890,9 @@ class Request extends stream_1.Duplex { total: this[kResponseSize] }; } + /** + Progress event for uploading (sending a request). + */ get uploadProgress() { let percent; if (this[kBodySize]) { @@ -31341,16 +31910,43 @@ class Request extends stream_1.Duplex { total: this[kBodySize] }; } + /** + 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() { var _a; return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings; } + /** + Whether the response was retrieved from the cache. + */ get isFromCache() { return this[kIsFromCache]; } - get _response() { - return this[kResponse]; - } pipe(destination, options) { if (this[kStartedReading]) { throw new Error('Failed to pipe. The response has been emitted already.'); @@ -31393,12 +31989,11 @@ module.exports = function(fn) { /***/ }), /***/ 950: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const url = __webpack_require__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; @@ -31413,7 +32008,7 @@ function getProxyUrl(reqUrl) { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { - proxyUrl = url.parse(proxyVar); + proxyUrl = new URL(proxyVar); } return proxyUrl; } @@ -31463,18 +32058,26 @@ exports.checkBypass = checkBypass; "use strict"; -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; Object.defineProperty(exports, "__esModule", { value: true }); const events_1 = __webpack_require__(614); -const getStream = __webpack_require__(145); +const is_1 = __webpack_require__(534); const PCancelable = __webpack_require__(557); -const calculate_retry_delay_1 = __webpack_require__(927); const types_1 = __webpack_require__(36); -const core_1 = __webpack_require__(468); -exports.PromisableRequest = core_1.default; +const parse_body_1 = __webpack_require__(121); +const core_1 = __webpack_require__(946); const proxy_events_1 = __webpack_require__(628); +const get_buffer_1 = __webpack_require__(284); +const is_response_ok_1 = __webpack_require__(422); const proxiedRequestEvents = [ 'request', 'response', @@ -31482,77 +32085,63 @@ const proxiedRequestEvents = [ 'uploadProgress', 'downloadProgress' ]; -function asPromise(options) { - let retryCount = 0; +function asPromise(normalizedOptions) { let globalRequest; let globalResponse; const emitter = new events_1.EventEmitter(); - const promise = new PCancelable((resolve, _reject, onCancel) => { - const makeRequest = () => { - // Support retries - // `options.throwHttpErrors` needs to be always true, - // so the HTTP errors are caught and the request is retried. - // The error is **eventually** thrown if the user value is true. - const { throwHttpErrors } = options; - if (!throwHttpErrors) { - options.throwHttpErrors = true; - } - // Note from @szmarczak: I think we should use `request.options` instead of the local options - const request = new core_1.default(options.url, options); + const promise = new PCancelable((resolve, reject, onCancel) => { + const makeRequest = (retryCount) => { + const request = new core_1.default(undefined, normalizedOptions); + request.retryCount = retryCount; request._noPipe = true; onCancel(() => request.destroy()); - const reject = async (error) => { - try { - for (const hook of options.hooks.beforeError) { - // eslint-disable-next-line no-await-in-loop - error = await hook(error); - } - } - catch (error_) { - _reject(new types_1.RequestError(error_.message, error_, request)); - return; - } - _reject(error); - }; + onCancel.shouldReject = false; + onCancel(() => reject(new types_1.CancelError(request))); globalRequest = request; - const onResponse = async (response) => { + request.once('response', async (response) => { + var _a; response.retryCount = retryCount; if (response.request.aborted) { // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error return; } - const isOk = () => { - const { statusCode } = response; - const limitStatusCode = options.followRedirect ? 299 : 399; - return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; - }; // Download body let rawBody; try { - rawBody = await getStream.buffer(request); + rawBody = await get_buffer_1.default(request); response.rawBody = rawBody; } - catch (_) { + catch (_b) { // The same error is caught below. // See request.once('error') return; } - // Parse body - try { - response.body = core_1.parseBody(response, options.responseType, options.parseJson, options.encoding); + if (request._isAboutToError) { + return; } - catch (error) { - // Fallback to `utf8` - response.body = rawBody.toString(); - if (isOk()) { - // TODO: Call `request._beforeError`, see https://github.com/nodejs/node/issues/32995 - reject(error); - return; + // Parse body + const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase(); + const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding); + const { options } = request; + if (isCompressed && !options.decompress) { + response.body = rawBody; + } + else { + try { + response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding); + } + catch (error) { + // Fallback to `utf8` + response.body = rawBody.toString(); + if (is_response_ok_1.isResponseOk(response)) { + request._beforeError(error); + return; + } } } try { for (const [index, hook] of options.hooks.afterResponse.entries()) { - // @ts-ignore TS doesn't notice that CancelableRequest is a Promise + // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise // eslint-disable-next-line no-await-in-loop response = await hook(response, async (updatedOptions) => { const typedOptions = core_1.default.normalizeArguments(undefined, { @@ -31580,84 +32169,41 @@ function asPromise(options) { } } catch (error) { - // TODO: Call `request._beforeError`, see https://github.com/nodejs/node/issues/32995 - reject(new types_1.RequestError(error.message, error, request)); + request._beforeError(new types_1.RequestError(error.message, error, request)); return; } - if (throwHttpErrors && !isOk()) { - reject(new types_1.HTTPError(response)); + if (!is_response_ok_1.isResponseOk(response)) { + request._beforeError(new types_1.HTTPError(response)); return; } globalResponse = response; - resolve(options.resolveBodyOnly ? response.body : response); - }; - request.once('response', onResponse); - request.once('error', async (error) => { + resolve(request.options.resolveBodyOnly ? response.body : response); + }); + const onError = (error) => { if (promise.isCanceled) { return; } - if (!request.options) { - reject(error); + const { options } = request; + if (error instanceof types_1.HTTPError && !options.throwHttpErrors) { + const { response } = error; + resolve(request.options.resolveBodyOnly ? response.body : response); return; } - request.off('response', onResponse); - let backoff; - retryCount++; - try { - backoff = await options.retry.calculateDelay({ - attemptCount: retryCount, - retryOptions: options.retry, - error, - computedValue: calculate_retry_delay_1.default({ - attemptCount: retryCount, - retryOptions: options.retry, - error, - computedValue: 0 - }) - }); - } - catch (error_) { - // Don't emit the `response` event - request.destroy(); - reject(new types_1.RequestError(error_.message, error, request)); - return; - } - if (backoff) { - // Don't emit the `response` event - request.destroy(); - const retry = async () => { - options.throwHttpErrors = throwHttpErrors; - try { - for (const hook of options.hooks.beforeRetry) { - // eslint-disable-next-line no-await-in-loop - await hook(options, error, retryCount); - } - } - catch (error_) { - // Don't emit the `response` event - request.destroy(); - reject(new types_1.RequestError(error_.message, error, request)); - return; - } - makeRequest(); - }; - setTimeout(retry, backoff); - return; - } - // The retry has not been made - retryCount--; - if (error instanceof types_1.HTTPError) { - // The error will be handled by the `response` event - onResponse(request._response); - return; - } - // Don't emit the `response` event - request.destroy(); reject(error); + }; + request.once('error', onError); + const previousBody = request.options.body; + request.once('retry', (newRetryCount, error) => { + var _a, _b; + if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) { + onError(error); + return; + } + makeRequest(newRetryCount); }); proxy_events_1.default(request, emitter, proxiedRequestEvents); }; - makeRequest(); + makeRequest(0); }); promise.on = (event, fn) => { emitter.on(event, fn); @@ -31667,14 +32213,16 @@ function asPromise(options) { const newPromise = (async () => { // Wait until downloading has ended await promise; - return core_1.parseBody(globalResponse, responseType, options.parseJson, options.encoding); + const { options } = globalResponse.request; + return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding); })(); Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); return newPromise; }; promise.json = () => { - if (!globalRequest.writableFinished && options.headers.accept === undefined) { - options.headers.accept = 'application/json'; + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && headers.accept === undefined) { + headers.accept = 'application/json'; } return shortcut('json'); }; @@ -31683,7 +32231,7 @@ function asPromise(options) { return promise; } exports.default = asPromise; -__export(__webpack_require__(36)); +__exportStar(__webpack_require__(36), exports); /***/ }), @@ -31724,7 +32272,7 @@ function validateAuth(auth) { const path = __webpack_require__(622); const childProcess = __webpack_require__(129); const crossSpawn = __webpack_require__(20); -const stripEof = __webpack_require__(768); +const stripEof = __webpack_require__(639); const npmRunPath = __webpack_require__(621); const isStream = __webpack_require__(323); const _getStream = __webpack_require__(79); @@ -32285,55 +32833,6 @@ function whichSync (cmd, opt) { } -/***/ }), - -/***/ 969: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var wrappy = __webpack_require__(11) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - /***/ }), /***/ 988: @@ -32445,14 +32944,17 @@ module.exports = async (input, options, callback) => { options = { ALPNProtocols: ['h2', 'http/1.1'], - protocol: 'https:', ...input, ...options, resolveSocket: true }; + if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { + throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); + } + + options.protocol = options.protocol || 'https:'; const isHttps = options.protocol === 'https:'; - const agents = options.agent; options.host = options.hostname || options.host || 'localhost'; options.session = options.tlsSession; @@ -32460,6 +32962,8 @@ module.exports = async (input, options, callback) => { options.port = options.port || (isHttps ? 443 : 80); options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; + const agents = options.agent; + if (agents) { if (agents.addRequest) { throw new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties'); @@ -32486,6 +32990,92 @@ module.exports = async (input, options, callback) => { module.exports.protocolCache = cache; +/***/ }), + +/***/ 992: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = __webpack_require__(534); +const normalizeArguments = (options, defaults) => { + if (is_1.default.null_(options.encoding)) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); + // `options.responseType` + if (options.responseType === undefined) { + options.responseType = 'text'; + } + // `options.retry` + const { retry } = options; + if (defaults) { + options.retry = { ...defaults.retry }; + } + else { + options.retry = { + calculateDelay: retryObject => retryObject.computedValue, + limit: 0, + methods: [], + statusCodes: [], + errorCodes: [], + maxRetryAfter: undefined + }; + } + if (is_1.default.object(retry)) { + options.retry = { + ...options.retry, + ...retry + }; + options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; + options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; + options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; + } + else if (is_1.default.number(retry)) { + options.retry.limit = retry; + } + if (is_1.default.undefined(options.retry.maxRetryAfter)) { + options.retry.maxRetryAfter = Math.min( + // TypeScript is not smart enough to handle `.filter(x => is.number(x))`. + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); + } + // `options.pagination` + if (is_1.default.object(options.pagination)) { + if (defaults) { + options.pagination = { + ...defaults.pagination, + ...options.pagination + }; + } + const { pagination } = options; + if (!is_1.default.function_(pagination.transform)) { + throw new Error('`options.pagination.transform` must be implemented'); + } + if (!is_1.default.function_(pagination.shouldContinue)) { + throw new Error('`options.pagination.shouldContinue` must be implemented'); + } + if (!is_1.default.function_(pagination.filter)) { + throw new TypeError('`options.pagination.filter` must be implemented'); + } + if (!is_1.default.function_(pagination.paginate)) { + throw new Error('`options.pagination.paginate` must be implemented'); + } + } + // JSON mode + if (options.responseType === 'json' && options.headers.accept === undefined) { + options.headers.accept = 'application/json'; + } + return options; +}; +exports.default = normalizeArguments; + + /***/ }) /******/ }, @@ -32514,5 +33104,36 @@ module.exports.protocolCache = cache; /******/ }; /******/ }(); /******/ +/******/ /* webpack/runtime/create fake namespace object */ +/******/ !function() { +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = this(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ }(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ !function() { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ }(); +/******/ /******/ } ); \ No newline at end of file