From 8d440d26bd1d10441af3d890d116ab7e88223047 Mon Sep 17 00:00:00 2001 From: MeilCli <2821921+MeilCli@users.noreply.github.com> Date: Thu, 3 Oct 2024 06:29:32 +0000 Subject: [PATCH] update actions --- dist/index.js | 22129 +++++++++++++++++++++++++----------------------- 1 file changed, 11429 insertions(+), 10700 deletions(-) diff --git a/dist/index.js b/dist/index.js index 3ccb576..0005a10 100644 --- a/dist/index.js +++ b/dist/index.js @@ -172,7 +172,11 @@ run(); 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]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -185,7 +189,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -247,13 +251,13 @@ class Command { } } function escapeData(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') @@ -271,7 +275,11 @@ function escapeProperty(s) { 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]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -284,7 +292,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -298,7 +306,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(4914); const file_command_1 = __nccwpck_require__(4753); const utils_1 = __nccwpck_require__(302); @@ -318,7 +326,7 @@ var ExitCode; * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +})(ExitCode || (exports.ExitCode = ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- @@ -329,13 +337,13 @@ var ExitCode; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); + const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } - command_1.issueCommand('set-env', { name }, convertedVal); + (0, command_1.issueCommand)('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -343,7 +351,7 @@ exports.exportVariable = exportVariable; * @param secret value of the secret */ function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); + (0, command_1.issueCommand)('add-mask', {}, secret); } exports.setSecret = setSecret; /** @@ -353,10 +361,10 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); + (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { - command_1.issueCommand('add-path', {}, inputPath); + (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } @@ -431,10 +439,10 @@ exports.getBooleanInput = getBooleanInput; function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** @@ -443,7 +451,7 @@ exports.setOutput = setOutput; * */ function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- @@ -474,7 +482,7 @@ exports.isDebug = isDebug; * @param message debug message */ function debug(message) { - command_1.issueCommand('debug', {}, message); + (0, command_1.issueCommand)('debug', {}, message); } exports.debug = debug; /** @@ -483,7 +491,7 @@ exports.debug = debug; * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** @@ -492,7 +500,7 @@ exports.error = error; * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** @@ -501,7 +509,7 @@ exports.warning = warning; * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** @@ -520,14 +528,14 @@ exports.info = info; * @param name The name of the output group */ function startGroup(name) { - command_1.issue('group', name); + (0, command_1.issue)('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { - command_1.issue('endgroup'); + (0, command_1.issue)('endgroup'); } exports.endGroup = endGroup; /** @@ -565,9 +573,9 @@ exports.group = group; function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } exports.saveState = saveState; /** @@ -603,6 +611,10 @@ var path_utils_1 = __nccwpck_require__(1976); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(8968)); //# sourceMappingURL=core.js.map /***/ }), @@ -615,7 +627,11 @@ Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: funct // For internal use, subject to change. 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]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -628,7 +644,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -638,7 +654,6 @@ exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(9896)); const os = __importStar(__nccwpck_require__(857)); -const uuid_1 = __nccwpck_require__(2048); const utils_1 = __nccwpck_require__(302); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; @@ -648,14 +663,14 @@ function issueFileCommand(command, message) { if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. @@ -740,9 +755,9 @@ class OidcClient { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - core_1.debug(`ID token url is ${id_token_url}`); + (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); + (0, core_1.setSecret)(id_token); return id_token; } catch (error) { @@ -763,7 +778,11 @@ exports.OidcClient = OidcClient; 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]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -776,7 +795,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -821,6 +840,107 @@ exports.toPlatformPath = toPlatformPath; /***/ }), +/***/ 8968: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(857)); +const exec = __importStar(__nccwpck_require__(5236)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + /***/ 1847: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -1158,71 +1278,14 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 7206: -/***/ (function(__unused_webpack_module, exports, __nccwpck_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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.hashFiles = exports.create = void 0; -const internal_globber_1 = __nccwpck_require__(103); -const internal_hash_files_1 = __nccwpck_require__(3608); -/** - * Constructs a globber - * - * @param patterns Patterns separated by newlines - * @param options Glob options - */ -function create(patterns, options) { - return __awaiter(this, void 0, void 0, function* () { - return yield internal_globber_1.DefaultGlobber.create(patterns, options); - }); -} -exports.create = create; -/** - * Computes the sha256 hash of a glob - * - * @param patterns Patterns separated by newlines - * @param currentWorkspace Workspace used when matching files - * @param options Glob options - * @param verbose Enables verbose logging - */ -function hashFiles(patterns, currentWorkspace = '', options, verbose = false) { - return __awaiter(this, void 0, void 0, function* () { - let followSymbolicLinks = true; - if (options && typeof options.followSymbolicLinks === 'boolean') { - followSymbolicLinks = options.followSymbolicLinks; - } - const globber = yield create(patterns, { followSymbolicLinks }); - return (0, internal_hash_files_1.hashFiles)(globber, currentWorkspace, verbose); - }); -} -exports.hashFiles = hashFiles; -//# sourceMappingURL=glob.js.map - -/***/ }), - -/***/ 8164: +/***/ 5236: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + 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]; @@ -1235,65 +1298,104 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOptions = void 0; -const core = __importStar(__nccwpck_require__(7484)); +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(3193); +const tr = __importStar(__nccwpck_require__(6665)); /** - * Returns a copy with defaults filled in. + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code */ -function getOptions(copy) { - const result = { - followSymbolicLinks: true, - implicitDescendants: true, - matchDirectories: true, - omitBrokenSymbolicLinks: true, - excludeHiddenFiles: false - }; - if (copy) { - if (typeof copy.followSymbolicLinks === 'boolean') { - result.followSymbolicLinks = copy.followSymbolicLinks; - core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); - } - if (typeof copy.implicitDescendants === 'boolean') { - result.implicitDescendants = copy.implicitDescendants; - core.debug(`implicitDescendants '${result.implicitDescendants}'`); - } - if (typeof copy.matchDirectories === 'boolean') { - result.matchDirectories = copy.matchDirectories; - core.debug(`matchDirectories '${result.matchDirectories}'`); - } - if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { - result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; - core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); - } - if (typeof copy.excludeHiddenFiles === 'boolean') { - result.excludeHiddenFiles = copy.excludeHiddenFiles; - core.debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`); +function exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } - } - return result; + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); } -exports.getOptions = getOptions; -//# sourceMappingURL=internal-glob-options-helper.js.map +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map /***/ }), -/***/ 103: +/***/ 6665: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + 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]; @@ -1306,7 +1408,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -1319,249 +1421,603 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } -var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DefaultGlobber = void 0; -const core = __importStar(__nccwpck_require__(7484)); -const fs = __importStar(__nccwpck_require__(9896)); -const globOptionsHelper = __importStar(__nccwpck_require__(8164)); +exports.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(857)); +const events = __importStar(__nccwpck_require__(4434)); +const child = __importStar(__nccwpck_require__(5317)); const path = __importStar(__nccwpck_require__(6928)); -const patternHelper = __importStar(__nccwpck_require__(8891)); -const internal_match_kind_1 = __nccwpck_require__(2644); -const internal_pattern_1 = __nccwpck_require__(5370); -const internal_search_state_1 = __nccwpck_require__(9890); +const io = __importStar(__nccwpck_require__(4994)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +const timers_1 = __nccwpck_require__(3557); +/* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; -class DefaultGlobber { - constructor(options) { - this.patterns = []; - this.searchPaths = []; - this.options = globOptionsHelper.getOptions(options); +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. + */ +class ToolRunner extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; } - getSearchPaths() { - // Return a copy - return this.searchPaths.slice(); + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } } - glob() { - var _a, e_1, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const result = []; - try { - for (var _d = true, _e = __asyncValues(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { - _c = _f.value; - _d = false; - const itemPath = _c; - result.push(itemPath); + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; } - finally { if (e_1) throw e_1.error; } } - return result; - }); - } - globGenerator() { - return __asyncGenerator(this, arguments, function* globGenerator_1() { - // Fill in defaults options - const options = globOptionsHelper.getOptions(this.options); - // Implicit descendants? - const patterns = []; - for (const pattern of this.patterns) { - patterns.push(pattern); - if (options.implicitDescendants && - (pattern.trailingSeparator || - pattern.segments[pattern.segments.length - 1] !== '**')) { - patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } - // Push the search paths - const stack = []; - for (const searchPath of patternHelper.getSearchPaths(patterns)) { - core.debug(`Search path '${searchPath}'`); - // Exists? - try { - // Intentionally using lstat. Detection for broken symlink - // will be performed later (if following symlinks). - yield __await(fs.promises.lstat(searchPath)); - } - catch (err) { - if (err.code === 'ENOENT') { - continue; - } - throw err; - } - stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); + } + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; } - // Search - const traversalChain = []; // used to detect cycles - while (stack.length) { - // Pop - const item = stack.pop(); - // Match? - const match = patternHelper.match(patterns, item.path); - const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); - if (!match && !partialMatch) { - continue; - } - // Stat - const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) - // Broken symlink, or symlink cycle detected, or no longer exists - ); - // Broken symlink, or symlink cycle detected, or no longer exists - if (!stats) { - continue; - } - // Hidden file or directory? - if (options.excludeHiddenFiles && path.basename(item.path).match(/^\./)) { - continue; - } - // Directory - if (stats.isDirectory()) { - // Matched - if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { - yield yield __await(item.path); - } - // Descend? - else if (!partialMatch) { - continue; - } - // Push the child items in reverse - const childLevel = item.level + 1; - const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); - stack.push(...childItems.reverse()); - } - // File - else if (match & internal_match_kind_1.MatchKind.File) { - yield yield __await(item.path); + } + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); + } + return s; + } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + return ''; + } + } + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; + } + } + return this.toolPath; + } + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += ' '; + argline += options.windowsVerbatimArguments + ? a + : this._windowsQuoteCmdArg(a); } + argline += '"'; + return [argline]; } - }); + } + return this.args; + } + _endsWith(str, end) { + return str.endsWith(end); + } + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return (this._endsWith(upperToolPath, '.CMD') || + this._endsWith(upperToolPath, '.BAT')); + } + _windowsQuoteCmdArg(arg) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); + } + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; + } + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } + } + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + if (!arg) { + // Need double quotation for empty argument + return '""'; + } + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '\\'; + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 10000 + }; + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; + } + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result['windowsVerbatimArguments'] = + options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; } /** - * Constructs a DefaultGlobber + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number */ - static create(patterns, options) { + exec() { return __awaiter(this, void 0, void 0, function* () { - const result = new DefaultGlobber(options); - if (IS_WINDOWS) { - patterns = patterns.replace(/\r\n/g, '\n'); - patterns = patterns.replace(/\r/g, '\n'); + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } - const lines = patterns.split('\n').map(x => x.trim()); - for (const line of lines) { - // Empty or comment - if (!line || line.startsWith('#')) { - continue; + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + this._debug(`exec tool: ${this.toolPath}`); + this._debug('arguments:'); + for (const arg of this.args) { + this._debug(` ${arg}`); } - // Pattern - else { - result.patterns.push(new internal_pattern_1.Pattern(line)); + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } - } - result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); - return result; - }); - } - static stat(item, options, traversalChain) { - return __awaiter(this, void 0, void 0, function* () { - // Note: - // `stat` returns info about the target of a symlink (or symlink chain) - // `lstat` returns info about a symlink itself - let stats; - if (options.followSymbolicLinks) { - try { - // Use `stat` (following symlinks) - stats = yield fs.promises.stat(item.path); + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); } - catch (err) { - if (err.code === 'ENOENT') { - if (options.omitBrokenSymbolicLinks) { - core.debug(`Broken symlink '${item.path}'`); - return undefined; + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ''; + if (cp.stdout) { + cp.stdout.on('data', (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); } - throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); + } + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + let errbuffer = ''; + if (cp.stderr) { + cp.stderr.on('data', (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && + optionsNonNull.errStream && + optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr + ? optionsNonNull.errStream + : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); + } + cp.on('error', (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on('exit', (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on('close', (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on('done', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); } - throw err; + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); } + })); + }); + } +} +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + if (escaped && c !== '"') { + arg += '\\'; + } + arg += c; + escaped = false; + } + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; } else { - // Use `lstat` (not following symlinks) - stats = yield fs.promises.lstat(item.path); + append(c); } - // Note, isDirectory() returns false for the lstat of a symlink - if (stats.isDirectory() && options.followSymbolicLinks) { - // Get the realpath - const realPath = yield fs.promises.realpath(item.path); - // Fixup the traversal chain to match the item level - while (traversalChain.length >= item.level) { - traversalChain.pop(); - } - // Test for a cycle - if (traversalChain.some((x) => x === realPath)) { - core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); - return undefined; - } - // Update the traversal chain - traversalChain.push(realPath); + continue; + } + if (c === '\\' && escaped) { + append(c); + continue; + } + if (c === '\\' && inQuotes) { + escaped = true; + continue; + } + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; } - return stats; - }); + continue; + } + append(c); + } + if (arg.length > 0) { + args.push(arg.trim()); } + return args; } -exports.DefaultGlobber = DefaultGlobber; -//# sourceMappingURL=internal-globber.js.map - -/***/ }), - -/***/ 3608: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error('toolPath must not be empty'); + } + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; + } } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } + else if (this.processExited) { + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + } + } + _debug(message) { + this.emit('debug', message); + } + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); + } + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); + } + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); + } +} +//# sourceMappingURL=toolrunner.js.map + +/***/ }), + +/***/ 7206: +/***/ (function(__unused_webpack_module, exports, __nccwpck_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) { @@ -1571,105 +2027,117 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.hashFiles = void 0; -const crypto = __importStar(__nccwpck_require__(6982)); -const core = __importStar(__nccwpck_require__(7484)); -const fs = __importStar(__nccwpck_require__(9896)); -const stream = __importStar(__nccwpck_require__(2203)); -const util = __importStar(__nccwpck_require__(9023)); -const path = __importStar(__nccwpck_require__(6928)); -function hashFiles(globber, currentWorkspace, verbose = false) { - var _a, e_1, _b, _c; - var _d; +exports.hashFiles = exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(103); +const internal_hash_files_1 = __nccwpck_require__(3608); +/** + * Constructs a globber + * + * @param patterns Patterns separated by newlines + * @param options Glob options + */ +function create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { - const writeDelegate = verbose ? core.info : core.debug; - let hasMatch = false; - const githubWorkspace = currentWorkspace - ? currentWorkspace - : (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd(); - const result = crypto.createHash('sha256'); - let count = 0; - try { - for (var _e = true, _f = __asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { - _c = _g.value; - _e = false; - const file = _c; - writeDelegate(file); - if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { - writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); - continue; - } - if (fs.statSync(file).isDirectory()) { - writeDelegate(`Skip directory '${file}'.`); - continue; - } - const hash = crypto.createHash('sha256'); - const pipeline = util.promisify(stream.pipeline); - yield pipeline(fs.createReadStream(file), hash); - result.write(hash.digest()); - count++; - if (!hasMatch) { - hasMatch = true; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); - } - finally { if (e_1) throw e_1.error; } - } - result.end(); - if (hasMatch) { - writeDelegate(`Found ${count} files to hash.`); - return result.digest('hex'); - } - else { - writeDelegate(`No matches found for glob`); - return ''; + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); +} +exports.create = create; +/** + * Computes the sha256 hash of a glob + * + * @param patterns Patterns separated by newlines + * @param currentWorkspace Workspace used when matching files + * @param options Glob options + * @param verbose Enables verbose logging + */ +function hashFiles(patterns, currentWorkspace = '', options, verbose = false) { + return __awaiter(this, void 0, void 0, function* () { + let followSymbolicLinks = true; + if (options && typeof options.followSymbolicLinks === 'boolean') { + followSymbolicLinks = options.followSymbolicLinks; } + const globber = yield create(patterns, { followSymbolicLinks }); + return (0, internal_hash_files_1.hashFiles)(globber, currentWorkspace, verbose); }); } exports.hashFiles = hashFiles; -//# sourceMappingURL=internal-hash-files.js.map +//# sourceMappingURL=glob.js.map /***/ }), -/***/ 2644: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8164: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MatchKind = void 0; +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(7484)); /** - * Indicates whether a pattern matches a path + * Returns a copy with defaults filled in. */ -var MatchKind; -(function (MatchKind) { - /** Not matched */ - MatchKind[MatchKind["None"] = 0] = "None"; - /** Matched if the path is a directory */ - MatchKind[MatchKind["Directory"] = 1] = "Directory"; - /** Matched if the path is a regular file */ - MatchKind[MatchKind["File"] = 2] = "File"; - /** Matched */ - MatchKind[MatchKind["All"] = 3] = "All"; -})(MatchKind || (exports.MatchKind = MatchKind = {})); -//# sourceMappingURL=internal-match-kind.js.map +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + matchDirectories: true, + omitBrokenSymbolicLinks: true, + excludeHiddenFiles: false + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); + } + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.matchDirectories === 'boolean') { + result.matchDirectories = copy.matchDirectories; + core.debug(`matchDirectories '${result.matchDirectories}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); + } + if (typeof copy.excludeHiddenFiles === 'boolean') { + result.excludeHiddenFiles = copy.excludeHiddenFiles; + core.debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`); + } + } + return result; +} +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), -/***/ 4138: +/***/ 103: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1697,188 +2165,231 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +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 __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(7484)); +const fs = __importStar(__nccwpck_require__(9896)); +const globOptionsHelper = __importStar(__nccwpck_require__(8164)); const path = __importStar(__nccwpck_require__(6928)); -const assert_1 = __importDefault(__nccwpck_require__(2613)); +const patternHelper = __importStar(__nccwpck_require__(8891)); +const internal_match_kind_1 = __nccwpck_require__(2644); +const internal_pattern_1 = __nccwpck_require__(5370); +const internal_search_state_1 = __nccwpck_require__(9890); const IS_WINDOWS = process.platform === 'win32'; -/** - * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. - * - * For example, on Linux/macOS: - * - `/ => /` - * - `/hello => /` - * - * For example, on Windows: - * - `C:\ => C:\` - * - `C:\hello => C:\` - * - `C: => C:` - * - `C:hello => C:` - * - `\ => \` - * - `\hello => \` - * - `\\hello => \\hello` - * - `\\hello\world => \\hello\world` - */ -function dirname(p) { - // Normalize slashes and trim unnecessary trailing slash - p = safeTrimTrailingSeparator(p); - // Windows UNC root, e.g. \\hello or \\hello\world - if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { - return p; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); } - // Get dirname - let result = path.dirname(p); - // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ - if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { - result = safeTrimTrailingSeparator(result); + getSearchPaths() { + // Return a copy + return this.searchPaths.slice(); } - return result; -} -exports.dirname = dirname; -/** - * Roots the path if not already rooted. On Windows, relative roots like `\` - * or `C:` are expanded based on the current working directory. - */ -function ensureAbsoluteRoot(root, itemPath) { - (0, assert_1.default)(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - (0, assert_1.default)(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); - // Already rooted - if (hasAbsoluteRoot(itemPath)) { - return itemPath; + glob() { + var _a, e_1, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const result = []; + try { + for (var _d = true, _e = __asyncValues(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const itemPath = _c; + result.push(itemPath); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + return result; + }); } - // Windows - if (IS_WINDOWS) { - // Check for itemPath like C: or C:foo - if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { - let cwd = process.cwd(); - (0, assert_1.default)(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - // Drive letter matches cwd? Expand to cwd - if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { - // Drive only, e.g. C: - if (itemPath.length === 2) { - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}`; + globGenerator() { + return __asyncGenerator(this, arguments, function* globGenerator_1() { + // Fill in defaults options + const options = globOptionsHelper.getOptions(this.options); + // Implicit descendants? + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && + (pattern.trailingSeparator || + pattern.segments[pattern.segments.length - 1] !== '**')) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); } - // Drive + path, e.g. C:foo - else { - if (!cwd.endsWith('\\')) { - cwd += '\\'; + } + // Push the search paths + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core.debug(`Search path '${searchPath}'`); + // Exists? + try { + // Intentionally using lstat. Detection for broken symlink + // will be performed later (if following symlinks). + yield __await(fs.promises.lstat(searchPath)); + } + catch (err) { + if (err.code === 'ENOENT') { + continue; } - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + throw err; } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); } - // Different drive - else { - return `${itemPath[0]}:\\${itemPath.substr(2)}`; + // Search + const traversalChain = []; // used to detect cycles + while (stack.length) { + // Pop + const item = stack.pop(); + // Match? + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + // Stat + const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + // Broken symlink, or symlink cycle detected, or no longer exists + if (!stats) { + continue; + } + // Hidden file or directory? + if (options.excludeHiddenFiles && path.basename(item.path).match(/^\./)) { + continue; + } + // Directory + if (stats.isDirectory()) { + // Matched + if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { + yield yield __await(item.path); + } + // Descend? + else if (!partialMatch) { + continue; + } + // Push the child items in reverse + const childLevel = item.level + 1; + const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } + // File + else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await(item.path); + } } - } - // Check for itemPath like \ or \foo - else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { - const cwd = process.cwd(); - (0, assert_1.default)(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - return `${cwd[0]}:\\${itemPath.substr(1)}`; - } + }); } - (0, assert_1.default)(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); - // Otherwise ensure root ends with a separator - if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { - // Intentionally empty + /** + * Constructs a DefaultGlobber + */ + static create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + const result = new DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, '\n'); + patterns = patterns.replace(/\r/g, '\n'); + } + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; + } + // Pattern + else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } + } + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; + }); } - else { - // Append separator - root += path.sep; + static stat(item, options, traversalChain) { + return __awaiter(this, void 0, void 0, function* () { + // Note: + // `stat` returns info about the target of a symlink (or symlink chain) + // `lstat` returns info about a symlink itself + let stats; + if (options.followSymbolicLinks) { + try { + // Use `stat` (following symlinks) + stats = yield fs.promises.stat(item.path); + } + catch (err) { + if (err.code === 'ENOENT') { + if (options.omitBrokenSymbolicLinks) { + core.debug(`Broken symlink '${item.path}'`); + return undefined; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); + } + // Note, isDirectory() returns false for the lstat of a symlink + if (stats.isDirectory() && options.followSymbolicLinks) { + // Get the realpath + const realPath = yield fs.promises.realpath(item.path); + // Fixup the traversal chain to match the item level + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + // Test for a cycle + if (traversalChain.some((x) => x === realPath)) { + core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return undefined; + } + // Update the traversal chain + traversalChain.push(realPath); + } + return stats; + }); } - return root + itemPath; } -exports.ensureAbsoluteRoot = ensureAbsoluteRoot; -/** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\\hello\share` and `C:\hello` (and using alternate separator). - */ -function hasAbsoluteRoot(itemPath) { - (0, assert_1.default)(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \\hello\share or C:\hello - return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); -} -exports.hasAbsoluteRoot = hasAbsoluteRoot; -/** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). - */ -function hasRoot(itemPath) { - (0, assert_1.default)(itemPath, `isRooted parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \ or \hello or \\hello - // E.g. C: or C:\hello - return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); -} -exports.hasRoot = hasRoot; -/** - * Removes redundant slashes and converts `/` to `\` on Windows - */ -function normalizeSeparators(p) { - p = p || ''; - // Windows - if (IS_WINDOWS) { - // Convert slashes on Windows - p = p.replace(/\//g, '\\'); - // Remove redundant slashes - const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello - return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC - } - // Remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -exports.normalizeSeparators = normalizeSeparators; -/** - * Normalizes the path separators and trims the trailing separator (when safe). - * For example, `/foo/ => /foo` but `/ => /` - */ -function safeTrimTrailingSeparator(p) { - // Short-circuit if empty - if (!p) { - return ''; - } - // Normalize separators - p = normalizeSeparators(p); - // No trailing slash - if (!p.endsWith(path.sep)) { - return p; - } - // Check '/' on Linux/macOS and '\' on Windows - if (p === path.sep) { - return p; - } - // On Windows check if drive root. E.g. C:\ - if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { - return p; - } - // Otherwise trim trailing slash - return p.substr(0, p.length - 1); -} -exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; -//# sourceMappingURL=internal-path-helper.js.map +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map /***/ }), -/***/ 6617: +/***/ 3608: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1906,103 +2417,114 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +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 __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Path = void 0; +exports.hashFiles = void 0; +const crypto = __importStar(__nccwpck_require__(6982)); +const core = __importStar(__nccwpck_require__(7484)); +const fs = __importStar(__nccwpck_require__(9896)); +const stream = __importStar(__nccwpck_require__(2203)); +const util = __importStar(__nccwpck_require__(9023)); const path = __importStar(__nccwpck_require__(6928)); -const pathHelper = __importStar(__nccwpck_require__(4138)); -const assert_1 = __importDefault(__nccwpck_require__(2613)); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Helper class for parsing paths into segments - */ -class Path { - /** - * Constructs a Path - * @param itemPath Path or array of segments - */ - constructor(itemPath) { - this.segments = []; - // String - if (typeof itemPath === 'string') { - (0, assert_1.default)(itemPath, `Parameter 'itemPath' must not be empty`); - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // Not rooted - if (!pathHelper.hasRoot(itemPath)) { - this.segments = itemPath.split(path.sep); - } - // Rooted - else { - // Add all segments, while not at the root - let remaining = itemPath; - let dir = pathHelper.dirname(remaining); - while (dir !== remaining) { - // Add the segment - const basename = path.basename(remaining); - this.segments.unshift(basename); - // Truncate the last segment - remaining = dir; - dir = pathHelper.dirname(remaining); +function hashFiles(globber, currentWorkspace, verbose = false) { + var _a, e_1, _b, _c; + var _d; + return __awaiter(this, void 0, void 0, function* () { + const writeDelegate = verbose ? core.info : core.debug; + let hasMatch = false; + const githubWorkspace = currentWorkspace + ? currentWorkspace + : (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd(); + const result = crypto.createHash('sha256'); + let count = 0; + try { + for (var _e = true, _f = __asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { + _c = _g.value; + _e = false; + const file = _c; + writeDelegate(file); + if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { + writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); + continue; } - // Remainder is the root - this.segments.unshift(remaining); - } - } - // Array - else { - // Must not be empty - (0, assert_1.default)(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); - // Each segment - for (let i = 0; i < itemPath.length; i++) { - let segment = itemPath[i]; - // Must not be empty - (0, assert_1.default)(segment, `Parameter 'itemPath' must not contain any empty segments`); - // Normalize slashes - segment = pathHelper.normalizeSeparators(itemPath[i]); - // Root segment - if (i === 0 && pathHelper.hasRoot(segment)) { - segment = pathHelper.safeTrimTrailingSeparator(segment); - (0, assert_1.default)(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); - this.segments.push(segment); + if (fs.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; } - // All other segments - else { - // Must not contain slash - (0, assert_1.default)(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); - this.segments.push(segment); + const hash = crypto.createHash('sha256'); + const pipeline = util.promisify(stream.pipeline); + yield pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; } } } - } - /** - * Converts the path to it's string representation - */ - toString() { - // First segment - let result = this.segments[0]; - // All others - let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); - for (let i = 1; i < this.segments.length; i++) { - if (skipSlash) { - skipSlash = false; - } - else { - result += path.sep; + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); } - result += this.segments[i]; + finally { if (e_1) throw e_1.error; } } - return result; - } + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest('hex'); + } + else { + writeDelegate(`No matches found for glob`); + return ''; + } + }); } -exports.Path = Path; -//# sourceMappingURL=internal-path.js.map +exports.hashFiles = hashFiles; +//# sourceMappingURL=internal-hash-files.js.map /***/ }), -/***/ 8891: +/***/ 2644: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; +/** + * Indicates whether a pattern matches a path + */ +var MatchKind; +(function (MatchKind) { + /** Not matched */ + MatchKind[MatchKind["None"] = 0] = "None"; + /** Matched if the path is a directory */ + MatchKind[MatchKind["Directory"] = 1] = "Directory"; + /** Matched if the path is a regular file */ + MatchKind[MatchKind["File"] = 2] = "File"; + /** Matched */ + MatchKind[MatchKind["All"] = 3] = "All"; +})(MatchKind || (exports.MatchKind = MatchKind = {})); +//# sourceMappingURL=internal-match-kind.js.map + +/***/ }), + +/***/ 4138: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2030,84 +2552,188 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.partialMatch = exports.match = exports.getSearchPaths = void 0; -const pathHelper = __importStar(__nccwpck_require__(4138)); -const internal_match_kind_1 = __nccwpck_require__(2644); +exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +const path = __importStar(__nccwpck_require__(6928)); +const assert_1 = __importDefault(__nccwpck_require__(2613)); const IS_WINDOWS = process.platform === 'win32'; /** - * Given an array of patterns, returns an array of paths to search. - * Duplicates and paths under other included paths are filtered out. + * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. + * + * For example, on Linux/macOS: + * - `/ => /` + * - `/hello => /` + * + * For example, on Windows: + * - `C:\ => C:\` + * - `C:\hello => C:\` + * - `C: => C:` + * - `C:hello => C:` + * - `\ => \` + * - `\hello => \` + * - `\\hello => \\hello` + * - `\\hello\world => \\hello\world` */ -function getSearchPaths(patterns) { - // Ignore negate patterns - patterns = patterns.filter(x => !x.negate); - // Create a map of all search paths - const searchPathMap = {}; - for (const pattern of patterns) { - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - searchPathMap[key] = 'candidate'; +function dirname(p) { + // Normalize slashes and trim unnecessary trailing slash + p = safeTrimTrailingSeparator(p); + // Windows UNC root, e.g. \\hello or \\hello\world + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; } - const result = []; - for (const pattern of patterns) { - // Check if already included - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - if (searchPathMap[key] === 'included') { - continue; - } - // Check for an ancestor search path - let foundAncestor = false; - let tempKey = key; - let parent = pathHelper.dirname(tempKey); - while (parent !== tempKey) { - if (searchPathMap[parent]) { - foundAncestor = true; - break; - } - tempKey = parent; - parent = pathHelper.dirname(tempKey); - } - // Include the search pattern in the result - if (!foundAncestor) { - result.push(pattern.searchPath); - searchPathMap[key] = 'included'; - } + // Get dirname + let result = path.dirname(p); + // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); } return result; } -exports.getSearchPaths = getSearchPaths; +exports.dirname = dirname; /** - * Matches the patterns against the path + * Roots the path if not already rooted. On Windows, relative roots like `\` + * or `C:` are expanded based on the current working directory. */ -function match(patterns, itemPath) { - let result = internal_match_kind_1.MatchKind.None; - for (const pattern of patterns) { - if (pattern.negate) { - result &= ~pattern.match(itemPath); +function ensureAbsoluteRoot(root, itemPath) { + (0, assert_1.default)(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + (0, assert_1.default)(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + // Already rooted + if (hasAbsoluteRoot(itemPath)) { + return itemPath; + } + // Windows + if (IS_WINDOWS) { + // Check for itemPath like C: or C:foo + if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { + let cwd = process.cwd(); + (0, assert_1.default)(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + // Drive letter matches cwd? Expand to cwd + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + // Drive only, e.g. C: + if (itemPath.length === 2) { + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}`; + } + // Drive + path, e.g. C:foo + else { + if (!cwd.endsWith('\\')) { + cwd += '\\'; + } + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } + } + // Different drive + else { + return `${itemPath[0]}:\\${itemPath.substr(2)}`; + } } - else { - result |= pattern.match(itemPath); + // Check for itemPath like \ or \foo + else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { + const cwd = process.cwd(); + (0, assert_1.default)(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + return `${cwd[0]}:\\${itemPath.substr(1)}`; } } - return result; + (0, assert_1.default)(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + // Otherwise ensure root ends with a separator + if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { + // Intentionally empty + } + else { + // Append separator + root += path.sep; + } + return root + itemPath; } -exports.match = match; +exports.ensureAbsoluteRoot = ensureAbsoluteRoot; /** - * Checks whether to descend further into the directory + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\\hello\share` and `C:\hello` (and using alternate separator). */ -function partialMatch(patterns, itemPath) { - return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +function hasAbsoluteRoot(itemPath) { + (0, assert_1.default)(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \\hello\share or C:\hello + return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); } -exports.partialMatch = partialMatch; -//# sourceMappingURL=internal-pattern-helper.js.map +exports.hasAbsoluteRoot = hasAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). + */ +function hasRoot(itemPath) { + (0, assert_1.default)(itemPath, `isRooted parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \ or \hello or \\hello + // E.g. C: or C:\hello + return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasRoot = hasRoot; +/** + * Removes redundant slashes and converts `/` to `\` on Windows + */ +function normalizeSeparators(p) { + p = p || ''; + // Windows + if (IS_WINDOWS) { + // Convert slashes on Windows + p = p.replace(/\//g, '\\'); + // Remove redundant slashes + const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello + return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC + } + // Remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +exports.normalizeSeparators = normalizeSeparators; +/** + * Normalizes the path separators and trims the trailing separator (when safe). + * For example, `/foo/ => /foo` but `/ => /` + */ +function safeTrimTrailingSeparator(p) { + // Short-circuit if empty + if (!p) { + return ''; + } + // Normalize separators + p = normalizeSeparators(p); + // No trailing slash + if (!p.endsWith(path.sep)) { + return p; + } + // Check '/' on Linux/macOS and '\' on Windows + if (p === path.sep) { + return p; + } + // On Windows check if drive root. E.g. C:\ + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + // Otherwise trim trailing slash + return p.substr(0, p.length - 1); +} +exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; +//# sourceMappingURL=internal-path-helper.js.map /***/ }), -/***/ 5370: +/***/ 6617: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2139,355 +2765,215 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Pattern = void 0; -const os = __importStar(__nccwpck_require__(857)); +exports.Path = void 0; const path = __importStar(__nccwpck_require__(6928)); const pathHelper = __importStar(__nccwpck_require__(4138)); const assert_1 = __importDefault(__nccwpck_require__(2613)); -const minimatch_1 = __nccwpck_require__(3772); -const internal_match_kind_1 = __nccwpck_require__(2644); -const internal_path_1 = __nccwpck_require__(6617); const IS_WINDOWS = process.platform === 'win32'; -class Pattern { - constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { - /** - * Indicates whether matches should be excluded from the result set - */ - this.negate = false; - // Pattern overload - let pattern; - if (typeof patternOrNegate === 'string') { - pattern = patternOrNegate.trim(); - } - // Segments overload - else { - // Convert to pattern - segments = segments || []; - (0, assert_1.default)(segments.length, `Parameter 'segments' must not empty`); - const root = Pattern.getLiteral(segments[0]); - (0, assert_1.default)(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); - pattern = new internal_path_1.Path(segments).toString().trim(); - if (patternOrNegate) { - pattern = `!${pattern}`; - } - } - // Negate - while (pattern.startsWith('!')) { - this.negate = !this.negate; - pattern = pattern.substr(1).trim(); - } - // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern, homedir); - // Segments - this.segments = new internal_path_1.Path(pattern).segments; - // Trailing slash indicates the pattern should only match directories, not regular files - this.trailingSeparator = pathHelper - .normalizeSeparators(pattern) - .endsWith(path.sep); - pattern = pathHelper.safeTrimTrailingSeparator(pattern); - // Search path (literal path prior to the first glob segment) - let foundGlob = false; - const searchSegments = this.segments - .map(x => Pattern.getLiteral(x)) - .filter(x => !foundGlob && !(foundGlob = x === '')); - this.searchPath = new internal_path_1.Path(searchSegments).toString(); - // Root RegExp (required when determining partial match) - this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); - this.isImplicitPattern = isImplicitPattern; - // Create minimatch - const minimatchOptions = { - dot: true, - nobrace: true, - nocase: IS_WINDOWS, - nocomment: true, - noext: true, - nonegate: true - }; - pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; - this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); - } +/** + * Helper class for parsing paths into segments + */ +class Path { /** - * Matches the pattern against the specified path + * Constructs a Path + * @param itemPath Path or array of segments */ - match(itemPath) { - // Last segment is globstar? - if (this.segments[this.segments.length - 1] === '**') { - // Normalize slashes - itemPath = pathHelper.normalizeSeparators(itemPath); - // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns - // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. - if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { - // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an absolute root. - itemPath = `${itemPath}${path.sep}`; - } - } - else { + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + (0, assert_1.default)(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - } - // Match - if (this.minimatch.match(itemPath)) { - return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; - } - return internal_match_kind_1.MatchKind.None; - } - /** - * Indicates whether the pattern may match descendants of the specified path - */ - partialMatch(itemPath) { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // matchOne does not handle root path correctly - if (pathHelper.dirname(itemPath) === itemPath) { - return this.rootRegExp.test(itemPath); - } - return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); - } - /** - * Escapes glob patterns within a path - */ - static globEscape(s) { - return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS - .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment - .replace(/\?/g, '[?]') // escape '?' - .replace(/\*/g, '[*]'); // escape '*' - } - /** - * Normalizes slashes and ensures absolute root - */ - static fixupPattern(pattern, homedir) { - // Empty - (0, assert_1.default)(pattern, 'pattern cannot be empty'); - // Must not contain `.` segment, unless first segment - // Must not contain `..` segment - const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - (0, assert_1.default)(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); - // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - (0, assert_1.default)(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); - // Normalize slashes - pattern = pathHelper.normalizeSeparators(pattern); - // Replace leading `.` segment - if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { - pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); - } - // Replace leading `~` segment - else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - homedir = homedir || os.homedir(); - (0, assert_1.default)(homedir, 'Unable to determine HOME directory'); - (0, assert_1.default)(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); - pattern = Pattern.globEscape(homedir) + pattern.substr(1); - } - // Replace relative drive root, e.g. pattern is C: or C:foo - else if (IS_WINDOWS && - (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); - if (pattern.length > 2 && !root.endsWith('\\')) { - root += '\\'; + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); } - pattern = Pattern.globEscape(root) + pattern.substr(2); - } - // Replace relative root, e.g. pattern is \ or \foo - else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); - if (!root.endsWith('\\')) { - root += '\\'; + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); } - pattern = Pattern.globEscape(root) + pattern.substr(1); } - // Otherwise ensure absolute root + // Array else { - pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); - } - return pathHelper.normalizeSeparators(pattern); - } - /** - * Attempts to unescape a pattern segment to create a literal path segment. - * Otherwise returns empty string. - */ - static getLiteral(segment) { - let literal = ''; - for (let i = 0; i < segment.length; i++) { - const c = segment[i]; - // Escape - if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { - literal += segment[++i]; - continue; - } - // Wildcard - else if (c === '*' || c === '?') { - return ''; - } - // Character set - else if (c === '[' && i + 1 < segment.length) { - let set = ''; - let closed = -1; - for (let i2 = i + 1; i2 < segment.length; i2++) { - const c2 = segment[i2]; - // Escape - if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { - set += segment[++i2]; - continue; - } - // Closed - else if (c2 === ']') { - closed = i2; - break; - } - // Otherwise - else { - set += c2; - } + // Must not be empty + (0, assert_1.default)(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + // Each segment + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + // Must not be empty + (0, assert_1.default)(segment, `Parameter 'itemPath' must not contain any empty segments`); + // Normalize slashes + segment = pathHelper.normalizeSeparators(itemPath[i]); + // Root segment + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + (0, assert_1.default)(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); } - // Closed? - if (closed >= 0) { - // Cannot convert - if (set.length > 1) { - return ''; - } - // Convert to literal - if (set) { - literal += set; - i = closed; - continue; - } + // All other segments + else { + // Must not contain slash + (0, assert_1.default)(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); } - // Otherwise fall thru } - // Append - literal += c; } - return literal; } /** - * Escapes regexp special characters - * https://javascript.info/regexp-escaping + * Converts the path to it's string representation */ - static regExpEscape(s) { - return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; } } -exports.Pattern = Pattern; -//# sourceMappingURL=internal-pattern.js.map +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map /***/ }), -/***/ 9890: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8891: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SearchState = void 0; -class SearchState { - constructor(path, level) { - this.path = path; - this.level = level; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } -} -exports.SearchState = SearchState; -//# sourceMappingURL=internal-search-state.js.map - -/***/ }), - -/***/ 4552: -/***/ (function(__unused_webpack_module, exports) { - -"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()); - }); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(4138)); +const internal_match_kind_1 = __nccwpck_require__(2644); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. + */ +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); } + return result; } -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); +exports.getSearchPaths = getSearchPaths; +/** + * Matches the patterns against the path + */ +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } + else { + result |= pattern.match(itemPath); } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); } + return result; } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map +exports.match = match; +/** + * Checks whether to descend further into the directory + */ +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +} +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map /***/ }), -/***/ 4844: +/***/ 5370: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ 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]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -2500,908 +2986,1232 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(8611)); -const https = __importStar(__nccwpck_require__(5692)); -const pm = __importStar(__nccwpck_require__(4988)); -const tunnel = __importStar(__nccwpck_require__(770)); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -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; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const pathHelper = __importStar(__nccwpck_require__(4138)); +const assert_1 = __importDefault(__nccwpck_require__(2613)); +const minimatch_1 = __nccwpck_require__(3772); +const internal_match_kind_1 = __nccwpck_require__(2644); +const internal_path_1 = __nccwpck_require__(6617); +const IS_WINDOWS = process.platform === 'win32'; +class Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + /** + * Indicates whether matches should be excluded from the result set + */ + this.negate = false; + // Pattern overload + let pattern; + if (typeof patternOrNegate === 'string') { + pattern = patternOrNegate.trim(); + } + // Segments overload + else { + // Convert to pattern + segments = segments || []; + (0, assert_1.default)(segments.length, `Parameter 'segments' must not empty`); + const root = Pattern.getLiteral(segments[0]); + (0, assert_1.default)(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; } } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); + // Negate + while (pattern.startsWith('!')) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + // Normalize slashes and ensures absolute root + pattern = Pattern.fixupPattern(pattern, homedir); + // Segments + this.segments = new internal_path_1.Path(pattern).segments; + // Trailing slash indicates the pattern should only match directories, not regular files + this.trailingSeparator = pathHelper + .normalizeSeparators(pattern) + .endsWith(path.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + // Search path (literal path prior to the first glob segment) + let foundGlob = false; + const searchSegments = this.segments + .map(x => Pattern.getLiteral(x)) + .filter(x => !foundGlob && !(foundGlob = x === '')); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + // Root RegExp (required when determining partial match) + this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; + // Create minimatch + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true + }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); } /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + * Matches the pattern against the specified path */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + match(itemPath) { + // Last segment is globstar? + if (this.segments[this.segments.length - 1] === '**') { + // Normalize slashes + itemPath = pathHelper.normalizeSeparators(itemPath); + // Append a trailing slash. Otherwise Minimatch will not match the directory immediately + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { + // Note, this is safe because the constructor ensures the pattern has an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + itemPath = `${itemPath}${path.sep}`; + } + } + else { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + // Match + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + } + return internal_match_kind_1.MatchKind.None; } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + /** + * Indicates whether the pattern may match descendants of the specified path + */ + partialMatch(itemPath) { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // matchOne does not handle root path correctly + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); + } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + /** + * Escapes glob patterns within a path + */ + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS + .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment + .replace(/\?/g, '[?]') // escape '?' + .replace(/\*/g, '[*]'); // escape '*' } /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch + * Normalizes slashes and ensures absolute root */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } + static fixupPattern(pattern, homedir) { + // Empty + (0, assert_1.default)(pattern, 'pattern cannot be empty'); + // Must not contain `.` segment, unless first segment + // Must not contain `..` segment + const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); + (0, assert_1.default)(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r + (0, assert_1.default)(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + // Normalize slashes + pattern = pathHelper.normalizeSeparators(pattern); + // Replace leading `.` segment + if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { + pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); + } + // Replace leading `~` segment + else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { + homedir = homedir || os.homedir(); + (0, assert_1.default)(homedir, 'Unable to determine HOME directory'); + (0, assert_1.default)(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + pattern = Pattern.globEscape(homedir) + pattern.substr(1); + } + // Replace relative drive root, e.g. pattern is C: or C:foo + else if (IS_WINDOWS && + (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(2); + } + // Replace relative root, e.g. pattern is \ or \foo + else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); + if (!root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(1); + } + // Otherwise ensure absolute root + else { + pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); + } + return pathHelper.normalizeSeparators(pattern); + } + /** + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. + */ + static getLiteral(segment) { + let literal = ''; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + // Escape + if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } + // Wildcard + else if (c === '*' || c === '?') { + return ''; + } + // Character set + else if (c === '[' && i + 1 < segment.length) { + let set = ''; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + // Escape + if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { + set += segment[++i2]; + continue; } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); + // Closed + else if (c2 === ']') { + closed = i2; + break; } + // Otherwise else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; + set += c2; } } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + // Closed? + if (closed >= 0) { + // Cannot convert + if (set.length > 1) { + return ''; } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } + // Convert to literal + if (set) { + literal += set; + i = closed; + continue; } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); } - } while (numTries < maxTries); - return response; - }); + // Otherwise fall thru + } + // Append + literal += c; + } + return literal; } /** - * Needs to be called if keepAlive is set to true in request options. + * Escapes regexp special characters + * https://javascript.info/regexp-escaping */ - dispose() { - if (this._agent) { - this._agent.destroy(); + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + } +} +exports.Pattern = Pattern; +//# sourceMappingURL=internal-pattern.js.map + +/***/ }), + +/***/ 9890: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; + } +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), + +/***/ 4552: +/***/ (function(__unused_webpack_module, exports) { + +"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()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - this._disposed = true; + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); + throw new Error('not implemented'); }); } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - return info; + options.headers['Authorization'] = `Bearer ${this.token}`; } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - return agent; + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); + // This handler cannot handle 401 + canHandleAuthentication() { + return false; } - _processResponse(res, options) { + handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); + throw new Error('not implemented'); }); } } -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map /***/ }), -/***/ 4988: -/***/ ((__unused_webpack_module, exports) => { +/***/ 4844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - return new URL(proxyVar); - } - else { - return undefined; - } +/* eslint-disable @typescript-eslint/no-explicit-any */ +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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(8611)); +const https = __importStar(__nccwpck_require__(5692)); +const pm = __importStar(__nccwpck_require__(4988)); +const tunnel = __importStar(__nccwpck_require__(770)); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +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); } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } } } - return false; -} -exports.checkBypass = checkBypass; -//# sourceMappingURL=proxy.js.map - -/***/ }), - -/***/ 9234: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* eslint-disable no-console */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ConsoleLogger = exports.LogLevel = void 0; -/** - * Severity levels for log entries - */ -var LogLevel; -(function (LogLevel) { - LogLevel["ERROR"] = "error"; - LogLevel["WARN"] = "warn"; - LogLevel["INFO"] = "info"; - LogLevel["DEBUG"] = "debug"; -})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); -/** - * Default logger which logs to stdout and stderr - */ -class ConsoleLogger { - constructor() { - this.level = LogLevel.INFO; - this.name = ''; + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - getLevel() { - return this.level; + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - /** - * Sets the instance's log level so that only messages which are equal or more severe are output to the console. - */ - setLevel(level) { - this.level = level; + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - /** - * Set the instance's name, which will appear on each log line before the message. + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ - setName(name) { - this.name = name; + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } /** - * Log a debug message + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - debug(...msg) { - if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.DEBUG, this.level)) { - console.debug(ConsoleLogger.labels.get(LogLevel.DEBUG), this.name, ...msg); - } + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); } /** - * Log an info message + * Needs to be called if keepAlive is set to true in request options. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - info(...msg) { - if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.INFO, this.level)) { - console.info(ConsoleLogger.labels.get(LogLevel.INFO), this.name, ...msg); + dispose() { + if (this._agent) { + this._agent.destroy(); } + this._disposed = true; } /** - * Log a warning message + * Raw request. + * @param info + * @param data */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - warn(...msg) { - if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.WARN, this.level)) { - console.warn(ConsoleLogger.labels.get(LogLevel.WARN), this.name, ...msg); - } + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); } /** - * Log an error message + * Raw request with callback. + * @param info + * @param data + * @param onResult */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error(...msg) { - if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.ERROR, this.level)) { - console.error(ConsoleLogger.labels.get(LogLevel.ERROR), this.name, ...msg); + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); } } /** - * Helper to compare two log levels and determine if a is equal or more severe than b + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ - static isMoreOrEqualSevere(a, b) { - return ConsoleLogger.severity[a] >= ConsoleLogger.severity[b]; + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } -} -exports.ConsoleLogger = ConsoleLogger; -/** Map of labels for each log level */ -ConsoleLogger.labels = (() => { - const entries = Object.entries(LogLevel); - const map = entries.map(([key, value]) => [value, `[${key}] `]); - return new Map(map); -})(); -/** Map of severity as comparable numbers for each log level */ -ConsoleLogger.severity = { - [LogLevel.ERROR]: 400, - [LogLevel.WARN]: 300, - [LogLevel.INFO]: 200, - [LogLevel.DEBUG]: 100, -}; + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); + } +} +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); //# sourceMappingURL=index.js.map /***/ }), -/***/ 4591: +/***/ 4988: /***/ ((__unused_webpack_module, exports) => { "use strict"; -// This file contains objects documented here: https://api.slack.com/reference/block-kit/block-elements Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=block-elements.js.map +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + return new URL(proxyVar); + } + else { + return undefined; + } +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; +//# sourceMappingURL=proxy.js.map /***/ }), -/***/ 1356: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// This file contains objects documented here: https://api.slack.com/reference/block-kit/blocks -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=blocks.js.map - -/***/ }), - -/***/ 3819: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// This file contains objects documented here: https://api.slack.com/reference/block-kit/composition-objects -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=composition-objects.js.map - -/***/ }), - -/***/ 4148: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=extensions.js.map - -/***/ }), - -/***/ 9110: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// These types represent users in Slack Calls, which is an API for showing 3rd party calls within the Slack client. -// More information on the API guide for Calls: https://api.slack.com/apis/calls -// and on User objects for use with Calls: https://api.slack.com/apis/calls#users -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=calls.js.map - -/***/ }), - -/***/ 5523: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=dialog.js.map - -/***/ }), - -/***/ 4775: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5207: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + 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); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(9110), exports); -__exportStar(__nccwpck_require__(5523), exports); -__exportStar(__nccwpck_require__(6999), exports); -__exportStar(__nccwpck_require__(5723), exports); -__exportStar(__nccwpck_require__(7445), exports); -__exportStar(__nccwpck_require__(1356), exports); -__exportStar(__nccwpck_require__(3819), exports); -__exportStar(__nccwpck_require__(4591), exports); -__exportStar(__nccwpck_require__(4148), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 5723: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=message-attachments.js.map - -/***/ }), - -/***/ 6999: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=message-metadata.js.map - -/***/ }), - -/***/ 7445: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=views.js.map +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(9896)); +const path = __importStar(__nccwpck_require__(6928)); +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' +exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); +} +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); +} +exports.isDirectory = isDirectory; +/** + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). + */ +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); + } + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + return p.startsWith('/'); +} +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); +} +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); + } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +} +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map /***/ }), -/***/ 4048: +/***/ 4994: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + 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]; @@ -3414,7 +4224,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -3427,827 +4237,538 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } -var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; - function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } - function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -}; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.buildThreadTsWarningMessage = exports.WebClient = exports.WebClientEvent = void 0; -const node_path_1 = __nccwpck_require__(6760); -const node_querystring_1 = __nccwpck_require__(1792); -const node_util_1 = __nccwpck_require__(7975); -const node_zlib_1 = __importDefault(__nccwpck_require__(8522)); -const axios_1 = __importDefault(__nccwpck_require__(7269)); -const form_data_1 = __importDefault(__nccwpck_require__(6454)); -const is_electron_1 = __importDefault(__nccwpck_require__(201)); -const is_stream_1 = __importDefault(__nccwpck_require__(6543)); -const p_queue_1 = __importDefault(__nccwpck_require__(6459)); -const p_retry_1 = __importStar(__nccwpck_require__(2103)); -const errors_1 = __nccwpck_require__(8486); -const file_upload_1 = __nccwpck_require__(2577); -const helpers_1 = __importDefault(__nccwpck_require__(4060)); -const instrument_1 = __nccwpck_require__(9224); -const logger_1 = __nccwpck_require__(4385); -const methods_1 = __nccwpck_require__(9339); -const retry_policies_1 = __nccwpck_require__(1766); -/* - * Helpers - */ -// Props on axios default headers object to ignore when retrieving full list of actual headers sent in any HTTP requests -const axiosHeaderPropsToIgnore = [ - 'delete', - 'common', - 'get', - 'put', - 'head', - 'post', - 'link', - 'patch', - 'purge', - 'unlink', - 'options', -]; -const defaultFilename = 'Untitled'; -const defaultPageSize = 200; -const noopPageReducer = () => undefined; -var WebClientEvent; -(function (WebClientEvent) { - // TODO: safe to rename this to conform to PascalCase enum type naming convention? - WebClientEvent["RATE_LIMITED"] = "rate_limited"; -})(WebClientEvent || (exports.WebClientEvent = WebClientEvent = {})); +exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(2613); +const path = __importStar(__nccwpck_require__(6928)); +const ioUtil = __importStar(__nccwpck_require__(5207)); /** - * A client for Slack's Web API + * Copies a file or folder. + * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * - * This client provides an alias for each {@link https://api.slack.com/methods|Web API method}. Each method is - * a convenience wrapper for calling the {@link WebClient#apiCall} method using the method name as the first parameter. + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. */ -class WebClient extends methods_1.Methods { - /** - * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`) - */ - constructor(token, { slackApiUrl = 'https://slack.com/api/', logger = undefined, logLevel = undefined, maxRequestConcurrency = 100, retryConfig = retry_policies_1.tenRetriesInAboutThirtyMinutes, agent = undefined, tls = undefined, timeout = 0, rejectRateLimitedCalls = false, headers = {}, teamId = undefined, attachOriginalToWebAPIRequestError = true, } = {}) { - super(); - this.token = token; - this.slackApiUrl = slackApiUrl; - this.retryConfig = retryConfig; - this.requestQueue = new p_queue_1.default({ concurrency: maxRequestConcurrency }); - // NOTE: may want to filter the keys to only those acceptable for TLS options - this.tlsConfig = tls !== undefined ? tls : {}; - this.rejectRateLimitedCalls = rejectRateLimitedCalls; - this.teamId = teamId; - this.attachOriginalToWebAPIRequestError = attachOriginalToWebAPIRequestError; - // Logging - if (typeof logger !== 'undefined') { - this.logger = logger; - if (typeof logLevel !== 'undefined') { - this.logger.debug('The logLevel given to WebClient was ignored as you also gave logger'); +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { + return; + } + // If dest is an existing directory, should copy inside. + const newDest = destStat && destStat.isDirectory() && copySourceDirectory + ? path.join(dest, path.basename(source)) + : dest; + if (!(yield ioUtil.exists(source))) { + throw new Error(`no such file or directory: ${source}`); + } + const sourceStat = yield ioUtil.stat(source); + if (sourceStat.isDirectory()) { + if (!recursive) { + throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); + } + else { + yield cpDirRecursive(source, newDest, 0, force); } } else { - this.logger = (0, logger_1.getLogger)(WebClient.loggerName, logLevel !== null && logLevel !== void 0 ? logLevel : logger_1.LogLevel.INFO, logger); - } - if (this.token && !headers.Authorization) - headers.Authorization = `Bearer ${this.token}`; - this.axios = axios_1.default.create({ - timeout, - baseURL: slackApiUrl, - headers: (0, is_electron_1.default)() ? headers : Object.assign({ 'User-Agent': (0, instrument_1.getUserAgent)() }, headers), - httpAgent: agent, - httpsAgent: agent, - transformRequest: [this.serializeApiCallOptions.bind(this)], - validateStatus: () => true, // all HTTP status codes should result in a resolved promise (as opposed to only 2xx) - maxRedirects: 0, - // disabling axios' automatic proxy support: - // axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations. - // for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other - // protocols), users of this package should use the `agent` option to configure a proxy. - proxy: false, - }); - // serializeApiCallOptions will always determine the appropriate content-type - this.axios.defaults.headers.post['Content-Type'] = undefined; - this.logger.debug('initialized'); - } - /** - * Generic method for calling a Web API method - * @param method - the Web API method to call {@link https://api.slack.com/methods} - * @param options - options - */ - apiCall(method, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - this.logger.debug(`apiCall('${method}') start`); - warnDeprecations(method, this.logger); - warnIfFallbackIsMissing(method, this.logger, options); - warnIfThreadTsIsNotString(method, this.logger, options); - if (typeof options === 'string' || typeof options === 'number' || typeof options === 'boolean') { - throw new TypeError(`Expected an options argument but instead received a ${typeof options}`); + if (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); } - (0, file_upload_1.warnIfNotUsingFilesUploadV2)(method, this.logger); - // @ts-expect-error insufficient overlap between Record and FilesUploadV2Arguments - if (method === 'files.uploadV2') - return this.filesUploadV2(options); - const headers = {}; - if (options.token) - headers.Authorization = `Bearer ${options.token}`; - const response = yield this.makeRequest(method, Object.assign({ team_id: this.teamId }, options), headers); - const result = yield this.buildResult(response); - this.logger.debug(`http request result: ${JSON.stringify(result)}`); - // log warnings in response metadata - if (result.response_metadata !== undefined && result.response_metadata.warnings !== undefined) { - result.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)); + yield copyFile(source, newDest, force); + } + }); +} +exports.cp = cp; +/** + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. + */ +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into dest + dest = path.join(dest, path.basename(source)); + destExists = yield ioUtil.exists(dest); } - // log warnings and errors in response metadata messages - // related to https://api.slack.com/changelog/2016-09-28-response-metadata-is-on-the-way - if (result.response_metadata !== undefined && result.response_metadata.messages !== undefined) { - for (const msg of result.response_metadata.messages) { - const errReg = /\[ERROR\](.*)/; - const warnReg = /\[WARN\](.*)/; - if (errReg.test(msg)) { - const errMatch = msg.match(errReg); - if (errMatch != null) { - this.logger.error(errMatch[1].trim()); - } - } - else if (warnReg.test(msg)) { - const warnMatch = msg.match(warnReg); - if (warnMatch != null) { - this.logger.warn(warnMatch[1].trim()); - } - } + if (destExists) { + if (options.force == null || options.force) { + yield rmRF(dest); + } + else { + throw new Error('Destination already exists'); } } - // If result's content is gzip, "ok" property is not returned with successful response - // TODO: look into simplifying this code block to only check for the second condition - // if an { ok: false } body applies for all API errors - if (!result.ok && response.headers['content-type'] !== 'application/gzip') { - throw (0, errors_1.platformErrorFromResult)(result); + } + yield mkdirP(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); +} +exports.mv = mv; +/** + * Remove a path recursively with force + * + * @param inputPath path to remove + */ +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // Check for invalid characters + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } - if ('ok' in result && result.ok === false) { - throw (0, errors_1.platformErrorFromResult)(result); + } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } + }); +} +exports.rmRF = rmRF; +/** + * Make a directory. Creates the full path with folders in between + * Will throw if it fails + * + * @param fsPath path to create + * @returns Promise + */ +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); +} +exports.mkdirP = mkdirP; +/** + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. + * + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool + */ +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // recursive when check=true + if (check) { + const result = yield which(tool, false); + if (!result) { + if (ioUtil.IS_WINDOWS) { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); + } + else { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); + } } - this.logger.debug(`apiCall('${method}') end`); return result; - }); - } - paginate(method, options, shouldStop, reduce) { - const pageSize = (() => { - if (options !== undefined && typeof options.limit === 'number') { - const { limit } = options; - options.limit = undefined; - return limit; - } - return defaultPageSize; - })(); - function generatePages() { - return __asyncGenerator(this, arguments, function* generatePages_1() { - // when result is undefined, that signals that the first of potentially many calls has not yet been made - let result; - // paginationOptions stores pagination options not already stored in the options argument - let paginationOptions = { - limit: pageSize, - }; - if (options !== undefined && options.cursor !== undefined) { - paginationOptions.cursor = options.cursor; + } + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); +} +exports.which = which; +/** + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool + */ +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); } - // NOTE: test for the situation where you're resuming a pagination using and existing cursor - while (result === undefined || paginationOptions !== undefined) { - result = yield __await(this.apiCall(method, Object.assign(options !== undefined ? options : {}, paginationOptions))); - yield yield __await(result); - paginationOptions = paginationOptionsForNextPage(result, pageSize); + } + } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); } - }); + } } - if (shouldStop === undefined) { - return generatePages.call(this); + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } } - const pageReducer = reduce !== undefined ? reduce : noopPageReducer; - let index = 0; - return (() => __awaiter(this, void 0, void 0, function* () { - // Unroll the first iteration of the iterator - // This is done primarily because in order to satisfy the type system, we need a variable that is typed as A - // (shown as accumulator before), but before the first iteration all we have is a variable typed A | undefined. - // Unrolling the first iteration allows us to deal with undefined as a special case. - var _a, e_1, _b, _c; - const pageIterator = generatePages.call(this); - const firstIteratorResult = yield pageIterator.next(undefined); - // Assumption: there will always be at least one result in a paginated API request - // if (firstIteratorResult.done) { return; } - const firstPage = firstIteratorResult.value; - let accumulator = pageReducer(undefined, firstPage, index); - index += 1; - if (shouldStop(firstPage)) { - return accumulator; + return matches; + }); +} +exports.findInPath = findInPath; +function readCopyOptions(options) { + const force = options.force == null ? true : options.force; + const recursive = Boolean(options.recursive); + const copySourceDirectory = options.copySourceDirectory == null + ? true + : Boolean(options.copySourceDirectory); + return { force, recursive, copySourceDirectory }; +} +function cpDirRecursive(sourceDir, destDir, currentDepth, force) { + return __awaiter(this, void 0, void 0, function* () { + // Ensure there is not a run away recursive copy + if (currentDepth >= 255) + return; + currentDepth++; + yield mkdirP(destDir); + const files = yield ioUtil.readdir(sourceDir); + for (const fileName of files) { + const srcFile = `${sourceDir}/${fileName}`; + const destFile = `${destDir}/${fileName}`; + const srcFileStat = yield ioUtil.lstat(srcFile); + if (srcFileStat.isDirectory()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } + else { + yield copyFile(srcFile, destFile, force); } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); +} +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it try { - // Continue iteration - for (var _d = true, pageIterator_1 = __asyncValues(pageIterator), pageIterator_1_1; pageIterator_1_1 = yield pageIterator_1.next(), _a = pageIterator_1_1.done, !_a; _d = true) { - _c = pageIterator_1_1.value; - _d = false; - const page = _c; - accumulator = pageReducer(accumulator, page, index); - if (shouldStop(page)) { - return accumulator; - } - index += 1; - } + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_d && !_a && (_b = pageIterator_1.return)) yield _b.call(pageIterator_1); + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); } - finally { if (e_1) throw e_1.error; } + // other errors = it doesn't exist, no work to do } - return accumulator; - }))(); - } - /** - * This wrapper method provides an easy way to upload files using the following endpoints: - * - * **#1**: For each file submitted with this method, submit filenames - * and file metadata to {@link https://api.slack.com/methods/files.getUploadURLExternal files.getUploadURLExternal} to request a URL to - * which to send the file data to and an id for the file - * - * **#2**: for each returned file `upload_url`, upload corresponding file to - * URLs returned from step 1 (e.g. https://files.slack.com/upload/v1/...\") - * - * **#3**: Complete uploads {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} - * @param options - */ - filesUploadV2(options) { - return __awaiter(this, void 0, void 0, function* () { - this.logger.debug('files.uploadV2() start'); - // 1 - const fileUploads = yield this.getAllFileUploads(options); - const fileUploadsURLRes = yield this.fetchAllUploadURLExternal(fileUploads); - // set the upload_url and file_id returned from Slack - fileUploadsURLRes.forEach((res, idx) => { - fileUploads[idx].upload_url = res.upload_url; - fileUploads[idx].file_id = res.file_id; - }); - // 2 - yield this.postFileUploadsToExternalURL(fileUploads, options); - // 3 - const completion = yield this.completeFileUploads(fileUploads); - return { ok: true, files: completion }; - }); + // Copy over symlink + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); + } + else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); + } + }); +} +//# sourceMappingURL=io.js.map + +/***/ }), + +/***/ 9234: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/* eslint-disable no-console */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConsoleLogger = exports.LogLevel = void 0; +/** + * Severity levels for log entries + */ +var LogLevel; +(function (LogLevel) { + LogLevel["ERROR"] = "error"; + LogLevel["WARN"] = "warn"; + LogLevel["INFO"] = "info"; + LogLevel["DEBUG"] = "debug"; +})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); +/** + * Default logger which logs to stdout and stderr + */ +class ConsoleLogger { + constructor() { + this.level = LogLevel.INFO; + this.name = ''; + } + getLevel() { + return this.level; } /** - * For each file submitted with this method, submits filenames - * and file metadata to files.getUploadURLExternal to request a URL to - * which to send the file data to and an id for the file - * @param fileUploads + * Sets the instance's log level so that only messages which are equal or more severe are output to the console. */ - fetchAllUploadURLExternal(fileUploads) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.all(fileUploads.map((upload) => { - const options = { - filename: upload.filename, - length: upload.length, - alt_text: upload.alt_text, - snippet_type: upload.snippet_type, - }; - if ('token' in upload) { - options.token = upload.token; - } - return this.files.getUploadURLExternal(options); - })); - }); + setLevel(level) { + this.level = level; } /** - * Complete uploads. - * @param fileUploads - * @returns + * Set the instance's name, which will appear on each log line before the message. */ - completeFileUploads(fileUploads) { - return __awaiter(this, void 0, void 0, function* () { - const toComplete = Object.values((0, file_upload_1.getAllFileUploadsToComplete)(fileUploads)); - return Promise.all(toComplete.map((job) => this.files.completeUploadExternal(job))); - }); + setName(name) { + this.name = name; } /** - * for each returned file upload URL, upload corresponding file - * @param fileUploads - * @returns + * Log a debug message */ - postFileUploadsToExternalURL(fileUploads, options) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.all(fileUploads.map((upload) => __awaiter(this, void 0, void 0, function* () { - const { upload_url, file_id, filename, data } = upload; - // either file or content will be defined - const body = data; - // try to post to external url - if (upload_url) { - const headers = {}; - if (options.token) - headers.Authorization = `Bearer ${options.token}`; - const uploadRes = yield this.makeRequest(upload_url, { - body, - }, headers); - if (uploadRes.status !== 200) { - return Promise.reject(Error(`Failed to upload file (id:${file_id}, filename: ${filename})`)); - } - const returnData = { ok: true, body: uploadRes.data }; - return Promise.resolve(returnData); - } - return Promise.reject(Error(`No upload url found for file (id: ${file_id}, filename: ${filename}`)); - }))); - }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + debug(...msg) { + if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.DEBUG, this.level)) { + console.debug(ConsoleLogger.labels.get(LogLevel.DEBUG), this.name, ...msg); + } } /** - * @param options All file uploads arguments - * @returns An array of file upload entries + * Log an info message */ - getAllFileUploads(options) { - return __awaiter(this, void 0, void 0, function* () { - let fileUploads = []; - // add single file data to uploads if file or content exists at the top level - if ('file' in options || 'content' in options) { - fileUploads.push(yield (0, file_upload_1.getFileUploadJob)(options, this.logger)); - } - // add multiple files data when file_uploads is supplied - if ('file_uploads' in options) { - fileUploads = fileUploads.concat(yield (0, file_upload_1.getMultipleFileUploadJobs)(options, this.logger)); - } - return fileUploads; - }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + info(...msg) { + if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.INFO, this.level)) { + console.info(ConsoleLogger.labels.get(LogLevel.INFO), this.name, ...msg); + } } /** - * Low-level function to make a single API request. handles queuing, retries, and http-level errors + * Log a warning message */ - makeRequest(url, body, headers = {}) { - return __awaiter(this, void 0, void 0, function* () { - // TODO: better input types - remove any - const task = () => this.requestQueue.add(() => __awaiter(this, void 0, void 0, function* () { - const requestURL = url.startsWith('https' || 0) ? url : `${this.axios.getUri() + url}`; - try { - // biome-ignore lint/suspicious/noExplicitAny: TODO: type this - const config = Object.assign({ headers }, this.tlsConfig); - // admin.analytics.getFile returns a binary response - // To be able to parse it, it should be read as an ArrayBuffer - if (url.endsWith('admin.analytics.getFile')) { - config.responseType = 'arraybuffer'; - } - // apps.event.authorizations.list will reject HTTP requests that send token in the body - // TODO: consider applying this change to all methods - though that will require thorough integration testing - if (url.endsWith('apps.event.authorizations.list')) { - body.token = undefined; - } - this.logger.debug(`http request url: ${requestURL}`); - this.logger.debug(`http request body: ${JSON.stringify(redact(body))}`); - // compile all headers - some set by default under the hood by axios - that will be sent along - let allHeaders = Object.keys(this.axios.defaults.headers).reduce((acc, cur) => { - if (!axiosHeaderPropsToIgnore.includes(cur)) { - acc[cur] = this.axios.defaults.headers[cur]; - } - return acc; - }, {}); - allHeaders = Object.assign(Object.assign(Object.assign({}, this.axios.defaults.headers.common), allHeaders), headers); - this.logger.debug(`http request headers: ${JSON.stringify(redact(allHeaders))}`); - const response = yield this.axios.post(url, body, config); - this.logger.debug('http response received'); - if (response.status === 429) { - const retrySec = parseRetryHeaders(response); - if (retrySec !== undefined) { - this.emit(WebClientEvent.RATE_LIMITED, retrySec, { url, body }); - if (this.rejectRateLimitedCalls) { - throw new p_retry_1.AbortError((0, errors_1.rateLimitedErrorWithDelay)(retrySec)); - } - this.logger.info(`API Call failed due to rate limiting. Will retry in ${retrySec} seconds.`); - // pause the request queue and then delay the rejection by the amount of time in the retry header - this.requestQueue.pause(); - // NOTE: if there was a way to introspect the current RetryOperation and know what the next timeout - // would be, then we could subtract that time from the following delay, knowing that it the next - // attempt still wouldn't occur until after the rate-limit header has specified. an even better - // solution would be to subtract the time from only the timeout of this next attempt of the - // RetryOperation. this would result in the staying paused for the entire duration specified in the - // header, yet this operation not having to pay the timeout cost in addition to that. - yield (0, helpers_1.default)(retrySec * 1000); - // resume the request queue and throw a non-abort error to signal a retry - this.requestQueue.start(); - // TODO: We may want to have more detailed info such as team_id, params except tokens, and so on. - throw new Error(`A rate limit was exceeded (url: ${url}, retry-after: ${retrySec})`); - } - // TODO: turn this into some CodedError - throw new p_retry_1.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${url}, retry-after header: ${response.headers['retry-after']})`)); - } - // Slack's Web API doesn't use meaningful status codes besides 429 and 200 - if (response.status !== 200) { - throw (0, errors_1.httpErrorFromResponse)(response); - } - return response; - } - catch (error) { - // To make this compatible with tsd, casting here instead of `catch (error: any)` - // biome-ignore lint/suspicious/noExplicitAny: errors can be anything - const e = error; - this.logger.warn('http request failed', e.message); - if (e.request) { - throw (0, errors_1.requestErrorWithOriginal)(e, this.attachOriginalToWebAPIRequestError); - } - throw error; - } - })); - // biome-ignore lint/suspicious/noExplicitAny: http responses can be anything - return (0, p_retry_1.default)(task, this.retryConfig); - }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + warn(...msg) { + if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.WARN, this.level)) { + console.warn(ConsoleLogger.labels.get(LogLevel.WARN), this.name, ...msg); + } } /** - * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either - * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used - * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type - * multipart/form-data. - * @param options - arguments for the Web API method - * @param headers - a mutable object representing the HTTP headers for the outgoing request + * Log an error message */ - serializeApiCallOptions(options, headers) { - // The following operation both flattens complex objects into a JSON-encoded strings and searches the values for - // binary content - let containsBinaryData = false; - // biome-ignore lint/suspicious/noExplicitAny: call options can be anything - const flattened = Object.entries(options).map(([key, value]) => { - if (value === undefined || value === null) { - return []; - } - let serializedValue = value; - if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { - containsBinaryData = true; - } - else if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') { - // if value is anything other than string, number, boolean, binary data, a Stream, or a Buffer, then encode it - // as a JSON string. - serializedValue = JSON.stringify(value); - } - return [key, serializedValue]; - }); - // A body with binary content should be serialized as multipart/form-data - if (containsBinaryData) { - this.logger.debug('Request arguments contain binary data'); - const form = flattened.reduce((frm, [key, value]) => { - if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { - const opts = {}; - opts.filename = (() => { - // attempt to find filename from `value`. adapted from: - // https://github.com/form-data/form-data/blob/028c21e0f93c5fefa46a7bbf1ba753e4f627ab7a/lib/form_data.js#L227-L230 - // formidable and the browser add a name property - // fs- and request- streams have path property - // biome-ignore lint/suspicious/noExplicitAny: form values can be anything - const streamOrBuffer = value; - if (typeof streamOrBuffer.name === 'string') { - return (0, node_path_1.basename)(streamOrBuffer.name); - } - if (typeof streamOrBuffer.path === 'string') { - return (0, node_path_1.basename)(streamOrBuffer.path); - } - return defaultFilename; - })(); - frm.append(key, value, opts); - } - else if (key !== undefined && value !== undefined) { - frm.append(key, value); - } - return frm; - }, new form_data_1.default()); - if (headers) { - // Copying FormData-generated headers into headers param - // not reassigning to headers param since it is passed by reference and behaves as an inout param - for (const [header, value] of Object.entries(form.getHeaders())) { - headers[header] = value; - } - } - return form; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error(...msg) { + if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.ERROR, this.level)) { + console.error(ConsoleLogger.labels.get(LogLevel.ERROR), this.name, ...msg); } - // Otherwise, a simple key-value object is returned - if (headers) - headers['Content-Type'] = 'application/x-www-form-urlencoded'; - // biome-ignore lint/suspicious/noExplicitAny: form values can be anything - const initialValue = {}; - return (0, node_querystring_1.stringify)(flattened.reduce((accumulator, [key, value]) => { - if (key !== undefined && value !== undefined) { - accumulator[key] = value; - } - return accumulator; - }, initialValue)); } /** - * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevant - * HTTP headers into the object. - * @param response - an http response + * Helper to compare two log levels and determine if a is equal or more severe than b */ - buildResult(response) { - return __awaiter(this, void 0, void 0, function* () { - let { data } = response; - const isGzipResponse = response.headers['content-type'] === 'application/gzip'; - // Check for GZIP response - if so, it is a successful response from admin.analytics.getFile - if (isGzipResponse) { - // admin.analytics.getFile will return a Buffer that can be unzipped - try { - const unzippedData = yield new Promise((resolve, reject) => { - node_zlib_1.default.unzip(data, (err, buf) => { - if (err) { - return reject(err); - } - return resolve(buf.toString().split('\n')); - }); - }) - .then((res) => res) - .catch((err) => { - throw err; - }); - const fileData = []; - if (Array.isArray(unzippedData)) { - for (const dataset of unzippedData) { - if (dataset && dataset.length > 0) { - fileData.push(JSON.parse(dataset)); - } - } - } - data = { file_data: fileData }; - } - catch (err) { - data = { ok: false, error: err }; - } - } - else if (!isGzipResponse && response.request.path === '/api/admin.analytics.getFile') { - // if it isn't a Gzip response but is from the admin.analytics.getFile request, - // decode the ArrayBuffer to JSON read the error - data = JSON.parse(new node_util_1.TextDecoder().decode(data)); - } - if (typeof data === 'string') { - // response.data can be a string, not an object for some reason - try { - data = JSON.parse(data); - } - catch (_) { - // failed to parse the string value as JSON data - data = { ok: false, error: data }; - } - } - if (data.response_metadata === undefined) { - data.response_metadata = {}; - } - // add scopes metadata from headers - if (response.headers['x-oauth-scopes'] !== undefined) { - data.response_metadata.scopes = response.headers['x-oauth-scopes'].trim().split(/\s*,\s*/); - } - if (response.headers['x-accepted-oauth-scopes'] !== undefined) { - data.response_metadata.acceptedScopes = response.headers['x-accepted-oauth-scopes'] - .trim() - .split(/\s*,\s*/); - } - // add retry metadata from headers - const retrySec = parseRetryHeaders(response); - if (retrySec !== undefined) { - data.response_metadata.retryAfter = retrySec; - } - return data; - }); - } -} -exports.WebClient = WebClient; -/** - * The name used to prefix all logging generated from this object - */ -WebClient.loggerName = 'WebClient'; -exports["default"] = WebClient; -/** - * Determines an appropriate set of cursor pagination options for the next request to a paginated API method. - * @param previousResult - the result of the last request, where the next cursor might be found. - * @param pageSize - the maximum number of additional items to fetch in the next request. - */ -function paginationOptionsForNextPage(previousResult, pageSize) { - if (previousResult !== undefined && - previousResult.response_metadata !== undefined && - previousResult.response_metadata.next_cursor !== undefined && - previousResult.response_metadata.next_cursor !== '') { - return { - limit: pageSize, - cursor: previousResult.response_metadata.next_cursor, - }; - } - return undefined; -} -/** - * Extract the amount of time (in seconds) the platform has recommended this client wait before sending another request - * from a rate-limited HTTP response (statusCode = 429). - */ -function parseRetryHeaders(response) { - if (response.headers['retry-after'] !== undefined) { - const retryAfter = Number.parseInt(response.headers['retry-after'], 10); - if (!Number.isNaN(retryAfter)) { - return retryAfter; - } - } - return undefined; -} -/** - * Log a warning when using a deprecated method - * @param method api method being called - * @param logger instance of web clients logger - */ -function warnDeprecations(method, logger) { - const deprecatedMethods = ['workflows.']; - const isDeprecated = deprecatedMethods.some((depMethod) => { - const re = new RegExp(`^${depMethod}`); - return re.test(method); - }); - if (isDeprecated) { - logger.warn(`${method} is deprecated. Please check on https://api.slack.com/methods for an alternative.`); - } -} -/** - * Log a warning when using chat.postMessage without text argument or attachments with fallback argument - * @param method api method being called - * @param logger instance of we clients logger - * @param options arguments for the Web API method - */ -function warnIfFallbackIsMissing(method, logger, options) { - const targetMethods = ['chat.postEphemeral', 'chat.postMessage', 'chat.scheduleMessage']; - const isTargetMethod = targetMethods.includes(method); - const hasAttachments = (args) => Array.isArray(args.attachments) && args.attachments.length; - const missingAttachmentFallbackDetected = (args) => Array.isArray(args.attachments) && - args.attachments.some((attachment) => !attachment.fallback || attachment.fallback.trim() === ''); - const isEmptyText = (args) => args.text === undefined || args.text === null || args.text === ''; - const buildMissingTextWarning = () => `The top-level \`text\` argument is missing in the request payload for a ${method} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`; - const buildMissingFallbackWarning = () => `Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${method} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://api.slack.com/reference/messaging/attachments#legacy_fields for more details).`; - if (isTargetMethod && typeof options === 'object') { - if (hasAttachments(options)) { - if (missingAttachmentFallbackDetected(options) && isEmptyText(options)) { - logger.warn(buildMissingTextWarning()); - logger.warn(buildMissingFallbackWarning()); - } - } - else if (isEmptyText(options)) { - logger.warn(buildMissingTextWarning()); - } - } -} -/** - * Log a warning when thread_ts is not a string - * @param method api method being called - * @param logger instance of web clients logger - * @param options arguments for the Web API method - */ -function warnIfThreadTsIsNotString(method, logger, options) { - const targetMethods = ['chat.postEphemeral', 'chat.postMessage', 'chat.scheduleMessage', 'files.upload']; - const isTargetMethod = targetMethods.includes(method); - if (isTargetMethod && (options === null || options === void 0 ? void 0 : options.thread_ts) !== undefined && typeof (options === null || options === void 0 ? void 0 : options.thread_ts) !== 'string') { - logger.warn(buildThreadTsWarningMessage(method)); + static isMoreOrEqualSevere(a, b) { + return ConsoleLogger.severity[a] >= ConsoleLogger.severity[b]; } } -function buildThreadTsWarningMessage(method) { - return `The given thread_ts value in the request payload for a ${method} call is a float value. We highly recommend using a string value instead.`; -} -exports.buildThreadTsWarningMessage = buildThreadTsWarningMessage; -/** - * Takes an object and redacts specific items - * @param body - * @returns - */ -function redact(body) { - // biome-ignore lint/suspicious/noExplicitAny: objects can be anything - const flattened = Object.entries(body).map(([key, value]) => { - // no value provided - if (value === undefined || value === null) { - return []; - } - let serializedValue = value; - // redact possible tokens - if (key.match(/.*token.*/) !== null || key.match(/[Aa]uthorization/)) { - serializedValue = '[[REDACTED]]'; - } - // when value is buffer or stream we can avoid logging it - if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { - serializedValue = '[[BINARY VALUE OMITTED]]'; - } - else if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') { - serializedValue = JSON.stringify(value); - } - return [key, serializedValue]; - }); - // return as object - const initialValue = {}; - return flattened.reduce((accumulator, [key, value]) => { - if (key !== undefined && value !== undefined) { - accumulator[key] = value; - } - return accumulator; - }, initialValue); -} -//# sourceMappingURL=WebClient.js.map +exports.ConsoleLogger = ConsoleLogger; +/** Map of labels for each log level */ +ConsoleLogger.labels = (() => { + const entries = Object.entries(LogLevel); + const map = entries.map(([key, value]) => [value, `[${key}] `]); + return new Map(map); +})(); +/** Map of severity as comparable numbers for each log level */ +ConsoleLogger.severity = { + [LogLevel.ERROR]: 400, + [LogLevel.WARN]: 300, + [LogLevel.INFO]: 200, + [LogLevel.DEBUG]: 100, +}; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 8486: +/***/ 4591: /***/ ((__unused_webpack_module, exports) => { "use strict"; +// This file contains objects documented here: https://api.slack.com/reference/block-kit/block-elements Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.rateLimitedErrorWithDelay = exports.platformErrorFromResult = exports.httpErrorFromResponse = exports.requestErrorWithOriginal = exports.errorWithCode = exports.ErrorCode = void 0; -/** - * A dictionary of codes for errors produced by this package - */ -var ErrorCode; -(function (ErrorCode) { - // general error - ErrorCode["RequestError"] = "slack_webapi_request_error"; - ErrorCode["HTTPError"] = "slack_webapi_http_error"; - ErrorCode["PlatformError"] = "slack_webapi_platform_error"; - ErrorCode["RateLimitedError"] = "slack_webapi_rate_limited_error"; - // file uploads errors - ErrorCode["FileUploadInvalidArgumentsError"] = "slack_webapi_file_upload_invalid_args_error"; - ErrorCode["FileUploadReadFileDataError"] = "slack_webapi_file_upload_read_file_data_error"; -})(ErrorCode || (exports.ErrorCode = ErrorCode = {})); -/** - * Factory for producing a {@link CodedError} from a generic error - */ -function errorWithCode(error, code) { - // NOTE: might be able to return something more specific than a CodedError with conditional typing - const codedError = error; - codedError.code = code; - return codedError; -} -exports.errorWithCode = errorWithCode; -/** - * A factory to create WebAPIRequestError objects - * @param original - original error - * @param attachOriginal - config indicating if 'original' property should be added on the error object - */ -function requestErrorWithOriginal(original, attachOriginal) { - const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError); - if (attachOriginal) { - error.original = original; - } - return error; -} -exports.requestErrorWithOriginal = requestErrorWithOriginal; -/** - * A factory to create WebAPIHTTPError objects - * @param response - original error - */ -function httpErrorFromResponse(response) { - const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError); - error.statusCode = response.status; - error.statusMessage = response.statusText; - const nonNullHeaders = {}; - for (const k of Object.keys(response.headers)) { - if (k && response.headers[k]) { - nonNullHeaders[k] = response.headers[k]; - } +//# sourceMappingURL=block-elements.js.map + +/***/ }), + +/***/ 1356: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// This file contains objects documented here: https://api.slack.com/reference/block-kit/blocks +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=blocks.js.map + +/***/ }), + +/***/ 3819: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// This file contains objects documented here: https://api.slack.com/reference/block-kit/composition-objects +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=composition-objects.js.map + +/***/ }), + +/***/ 4148: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=extensions.js.map + +/***/ }), + +/***/ 9110: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// These types represent users in Slack Calls, which is an API for showing 3rd party calls within the Slack client. +// More information on the API guide for Calls: https://api.slack.com/apis/calls +// and on User objects for use with Calls: https://api.slack.com/apis/calls#users +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=calls.js.map + +/***/ }), + +/***/ 5523: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=dialog.js.map + +/***/ }), + +/***/ 4775: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - error.headers = nonNullHeaders; - error.body = response.data; - return error; -} -exports.httpErrorFromResponse = httpErrorFromResponse; -/** - * A factory to create WebAPIPlatformError objects - * @param result - Web API call result - */ -function platformErrorFromResult(result) { - const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError); - error.data = result; - return error; -} -exports.platformErrorFromResult = platformErrorFromResult; -/** - * A factory to create WebAPIRateLimitedError objects - * @param retrySec - Number of seconds that the request can be retried in - */ -function rateLimitedErrorWithDelay(retrySec) { - const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError); - error.retryAfter = retrySec; - return error; -} -exports.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay; -//# sourceMappingURL=errors.js.map + Object.defineProperty(o, k2, desc); +}) : (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 })); +__exportStar(__nccwpck_require__(9110), exports); +__exportStar(__nccwpck_require__(5523), exports); +__exportStar(__nccwpck_require__(6999), exports); +__exportStar(__nccwpck_require__(5723), exports); +__exportStar(__nccwpck_require__(7445), exports); +__exportStar(__nccwpck_require__(1356), exports); +__exportStar(__nccwpck_require__(3819), exports); +__exportStar(__nccwpck_require__(4591), exports); +__exportStar(__nccwpck_require__(4148), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 2577: +/***/ 5723: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=message-attachments.js.map + +/***/ }), + +/***/ 6999: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=message-metadata.js.map + +/***/ }), + +/***/ 7445: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=views.js.map + +/***/ }), + +/***/ 4048: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -4257,9376 +4778,9560 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.buildInvalidFilesUploadParamError = exports.buildMultipleChannelsErrorMsg = exports.buildChannelsWarning = exports.buildFilesUploadMissingMessage = exports.buildGeneralFilesUploadWarning = exports.buildLegacyMethodWarning = exports.buildMissingExtensionWarning = exports.buildMissingFileNameWarning = exports.buildLegacyFileTypeWarning = exports.buildFileSizeErrorMsg = exports.buildMissingFileIdError = exports.warnIfLegacyFileType = exports.warnIfMissingOrInvalidFileNameAndDefault = exports.errorIfInvalidOrMissingFileData = exports.errorIfChannelsCsv = exports.warnIfChannels = exports.warnIfNotUsingFilesUploadV2 = exports.getAllFileUploadsToComplete = exports.getFileDataAsStream = exports.getFileDataLength = exports.getFileData = exports.getMultipleFileUploadJobs = exports.getFileUploadJob = void 0; -const node_fs_1 = __nccwpck_require__(3024); -const node_stream_1 = __nccwpck_require__(7075); -const errors_1 = __nccwpck_require__(8486); -function getFileUploadJob(options, logger) { - var _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - // Validate parameters - warnIfLegacyFileType(options, logger); - warnIfChannels(options, logger); - errorIfChannelsCsv(options); - const fileName = warnIfMissingOrInvalidFileNameAndDefault(options, logger); - const fileData = yield getFileData(options); - const fileDataBytesLength = getFileDataLength(fileData); - const fileUploadJob = { - // supplied by user - alt_text: options.alt_text, - channel_id: (_a = options.channels) !== null && _a !== void 0 ? _a : options.channel_id, - filename: (_b = options.filename) !== null && _b !== void 0 ? _b : fileName, - initial_comment: options.initial_comment, - snippet_type: options.snippet_type, - title: (_d = (_c = options.title) !== null && _c !== void 0 ? _c : options.filename) !== null && _d !== void 0 ? _d : fileName, // default title to filename unless otherwise specified - // calculated - data: fileData, - length: fileDataBytesLength, - }; - if ('thread_ts' in options) { - fileUploadJob.thread_ts = options.thread_ts; - } - if ('token' in options) { - fileUploadJob.token = options.token; - } - if ('content' in options) { - return Object.assign({ content: options.content }, fileUploadJob); - } - if ('file' in options) { - return Object.assign({ file: options.file }, fileUploadJob); - } - throw (0, errors_1.errorWithCode)(new Error('Either a file or content field is required for valid file upload. You must supply one'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - }); -} -exports.getFileUploadJob = getFileUploadJob; -/** - * Returns an array of files upload entries when `file_uploads` is supplied. - * **Note** - * file_uploads should be set when multiple files are intended to be attached to a - * single message. To support this, we handle options supplied with - * top level `initial_comment`, `thread_ts`, `channel_id` and `file_uploads` parameters. - * ```javascript - * const res = await client.files.uploadV2({ - * initial_comment: 'Here are the files!', - * thread_ts: '1223313423434.131321', - * channel_id: 'C12345', - * file_uploads: [ - * { - * file: './test/fixtures/test-txt.txt', - * filename: 'test-txt.txt', - * }, - * { - * file: './test/fixtures/test-png.png', - * filename: 'test-png.png', - * }, - * ], - * }); - * ``` - * @param options provided by user - */ -function getMultipleFileUploadJobs(options, logger) { - return __awaiter(this, void 0, void 0, function* () { - if ('file_uploads' in options) { - // go through each file_upload and create a job for it - return Promise.all(options.file_uploads.map((upload) => { - // ensure no omitted properties included in files_upload entry - // these properties are valid only at the top-level, not - // inside file_uploads. - const { channel_id, channels, initial_comment, thread_ts } = upload; - if (channel_id || channels || initial_comment || thread_ts) { - throw (0, errors_1.errorWithCode)(new Error(buildInvalidFilesUploadParamError()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - // takes any channel_id, initial_comment and thread_ts - // supplied at the top level. - const uploadJobArgs = Object.assign(Object.assign({}, upload), { channels: options.channels, channel_id: options.channel_id, initial_comment: options.initial_comment }); - if ('thread_ts' in options) { - uploadJobArgs.thread_ts = options.thread_ts; - } - if ('token' in options) { - uploadJobArgs.token = options.token; - } - if ('content' in upload) { - return getFileUploadJob(Object.assign({ content: upload.content }, uploadJobArgs), logger); - } - if ('file' in upload) { - return getFileUploadJob(Object.assign({ file: upload.file }, uploadJobArgs), logger); - } - throw (0, errors_1.errorWithCode)(new Error('Either a file or content field is required for valid file upload. You must supply one'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - })); - } - throw new Error(buildFilesUploadMissingMessage()); - }); -} -exports.getMultipleFileUploadJobs = getMultipleFileUploadJobs; -// Helpers to build the FileUploadJob -/** - * Returns a single file upload's data - * @param options - * @returns Binary data representation of file +exports.buildThreadTsWarningMessage = exports.WebClient = exports.WebClientEvent = void 0; +const node_path_1 = __nccwpck_require__(6760); +const node_querystring_1 = __nccwpck_require__(1792); +const node_util_1 = __nccwpck_require__(7975); +const node_zlib_1 = __importDefault(__nccwpck_require__(8522)); +const axios_1 = __importDefault(__nccwpck_require__(7269)); +const form_data_1 = __importDefault(__nccwpck_require__(6454)); +const is_electron_1 = __importDefault(__nccwpck_require__(201)); +const is_stream_1 = __importDefault(__nccwpck_require__(6543)); +const p_queue_1 = __importDefault(__nccwpck_require__(6459)); +const p_retry_1 = __importStar(__nccwpck_require__(2103)); +const errors_1 = __nccwpck_require__(8486); +const file_upload_1 = __nccwpck_require__(2577); +const helpers_1 = __importDefault(__nccwpck_require__(4060)); +const instrument_1 = __nccwpck_require__(9224); +const logger_1 = __nccwpck_require__(4385); +const methods_1 = __nccwpck_require__(9339); +const retry_policies_1 = __nccwpck_require__(1766); +/* + * Helpers */ -function getFileData(options) { - return __awaiter(this, void 0, void 0, function* () { - errorIfInvalidOrMissingFileData(options); - if ('file' in options) { - const { file } = options; - // try to handle as buffer - if (Buffer.isBuffer(file)) - return file; - // try to handle as filepath - if (typeof file === 'string') { - // try to read file as if the string was a file path - try { - const dataBuffer = (0, node_fs_1.readFileSync)(file); - return dataBuffer; - } - catch (error) { - throw (0, errors_1.errorWithCode)(new Error(`Unable to resolve file data for ${file}. Please supply a filepath string, or binary data Buffer or String directly.`), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - } - // try to handle as Readable - const data = yield getFileDataAsStream(file); - if (data) - return data; - } - if ('content' in options) - return Buffer.from(options.content); - // general catch-all error - throw (0, errors_1.errorWithCode)(new Error('There was an issue getting the file data for the file or content supplied'), errors_1.ErrorCode.FileUploadReadFileDataError); - }); -} -exports.getFileData = getFileData; -function getFileDataLength(data) { - if (data) { - return Buffer.byteLength(data, 'utf8'); - } - throw (0, errors_1.errorWithCode)(new Error(buildFileSizeErrorMsg()), errors_1.ErrorCode.FileUploadReadFileDataError); -} -exports.getFileDataLength = getFileDataLength; -function getFileDataAsStream(readable) { - return __awaiter(this, void 0, void 0, function* () { - const chunks = []; - return new Promise((resolve, reject) => { - readable.on('readable', () => { - let chunk; - // biome-ignore lint/suspicious/noAssignInExpressions: being terse, this is OK - while ((chunk = readable.read()) !== null) { - chunks.push(chunk); - } - }); - readable.on('end', () => { - if (chunks.length > 0) { - const content = Buffer.concat(chunks); - resolve(content); - } - else { - reject(Error('No data in supplied file')); - } - }); - }); - }); -} -exports.getFileDataAsStream = getFileDataAsStream; +// Props on axios default headers object to ignore when retrieving full list of actual headers sent in any HTTP requests +const axiosHeaderPropsToIgnore = [ + 'delete', + 'common', + 'get', + 'put', + 'head', + 'post', + 'link', + 'patch', + 'purge', + 'unlink', + 'options', +]; +const defaultFilename = 'Untitled'; +const defaultPageSize = 200; +const noopPageReducer = () => undefined; +var WebClientEvent; +(function (WebClientEvent) { + // TODO: safe to rename this to conform to PascalCase enum type naming convention? + WebClientEvent["RATE_LIMITED"] = "rate_limited"; +})(WebClientEvent || (exports.WebClientEvent = WebClientEvent = {})); /** - * Filters through all fileUploads and groups them into jobs for completion - * based on combination of channel_id, thread_ts, initial_comment. - * {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} allows for multiple - * files to be uploaded with a message (`initial_comment`), and as a threaded message (`thread_ts`) - * In order to be grouped together, file uploads must have like properties. - * @param fileUploads - * @returns + * A client for Slack's Web API + * + * This client provides an alias for each {@link https://api.slack.com/methods|Web API method}. Each method is + * a convenience wrapper for calling the {@link WebClient#apiCall} method using the method name as the first parameter. */ -function getAllFileUploadsToComplete(fileUploads) { - const toComplete = {}; - for (const upload of fileUploads) { - const { channel_id, thread_ts, initial_comment, file_id, title } = upload; - if (file_id) { - const compareString = `:::${channel_id}:::${thread_ts}:::${initial_comment}`; - if (!Object.prototype.hasOwnProperty.call(toComplete, compareString)) { - toComplete[compareString] = { - files: [{ id: file_id, title }], - channel_id, - initial_comment, - }; - if (thread_ts) { - toComplete[compareString].thread_ts = upload.thread_ts; - } - if ('token' in upload) { - toComplete[compareString].token = upload.token; - } - } - else { - toComplete[compareString].files.push({ - id: file_id, - title, - }); +class WebClient extends methods_1.Methods { + /** + * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`) + */ + constructor(token, { slackApiUrl = 'https://slack.com/api/', logger = undefined, logLevel = undefined, maxRequestConcurrency = 100, retryConfig = retry_policies_1.tenRetriesInAboutThirtyMinutes, agent = undefined, tls = undefined, timeout = 0, rejectRateLimitedCalls = false, headers = {}, teamId = undefined, attachOriginalToWebAPIRequestError = true, } = {}) { + super(); + this.token = token; + this.slackApiUrl = slackApiUrl; + this.retryConfig = retryConfig; + this.requestQueue = new p_queue_1.default({ concurrency: maxRequestConcurrency }); + // NOTE: may want to filter the keys to only those acceptable for TLS options + this.tlsConfig = tls !== undefined ? tls : {}; + this.rejectRateLimitedCalls = rejectRateLimitedCalls; + this.teamId = teamId; + this.attachOriginalToWebAPIRequestError = attachOriginalToWebAPIRequestError; + // Logging + if (typeof logger !== 'undefined') { + this.logger = logger; + if (typeof logLevel !== 'undefined') { + this.logger.debug('The logLevel given to WebClient was ignored as you also gave logger'); } } else { - throw new Error(buildMissingFileIdError()); + this.logger = (0, logger_1.getLogger)(WebClient.loggerName, logLevel !== null && logLevel !== void 0 ? logLevel : logger_1.LogLevel.INFO, logger); } + if (this.token && !headers.Authorization) + headers.Authorization = `Bearer ${this.token}`; + this.axios = axios_1.default.create({ + timeout, + baseURL: slackApiUrl, + headers: (0, is_electron_1.default)() ? headers : Object.assign({ 'User-Agent': (0, instrument_1.getUserAgent)() }, headers), + httpAgent: agent, + httpsAgent: agent, + transformRequest: [this.serializeApiCallOptions.bind(this)], + validateStatus: () => true, // all HTTP status codes should result in a resolved promise (as opposed to only 2xx) + maxRedirects: 0, + // disabling axios' automatic proxy support: + // axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations. + // for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other + // protocols), users of this package should use the `agent` option to configure a proxy. + proxy: false, + }); + // serializeApiCallOptions will always determine the appropriate content-type + this.axios.defaults.headers.post['Content-Type'] = undefined; + this.logger.debug('initialized'); } - return toComplete; -} -exports.getAllFileUploadsToComplete = getAllFileUploadsToComplete; -// Validation -/** - * Advise to use the files.uploadV2 method over legacy files.upload method and over - * lower-level utilities. - * @param method - * @param logger - */ -function warnIfNotUsingFilesUploadV2(method, logger) { - const targetMethods = ['files.upload']; - const isTargetMethod = targetMethods.includes(method); - if (method === 'files.upload') - logger.warn(buildLegacyMethodWarning(method)); - if (isTargetMethod) - logger.info(buildGeneralFilesUploadWarning()); -} -exports.warnIfNotUsingFilesUploadV2 = warnIfNotUsingFilesUploadV2; -/** - * `channels` param is supported but only when a single channel is specified. - * @param options - * @param logger - */ -function warnIfChannels(options, logger) { - if (options.channels) - logger.warn(buildChannelsWarning()); -} -exports.warnIfChannels = warnIfChannels; -/** - * v1 files.upload supported `channels` parameter provided as a comma-separated - * string of values, e.g. 'C1234,C5678'. V2 no longer supports this csv value. - * You may still supply `channels` with a single channel string value e.g. 'C1234' - * but it is highly encouraged to supply `channel_id` instead. - * @param options - */ -function errorIfChannelsCsv(options) { - const channels = options.channels ? options.channels.split(',') : []; - if (channels.length > 1) { - throw (0, errors_1.errorWithCode)(new Error(buildMultipleChannelsErrorMsg()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } -} -exports.errorIfChannelsCsv = errorIfChannelsCsv; -/** - * Checks for either a file or content property and errors if missing - * @param options - */ -function errorIfInvalidOrMissingFileData(options) { - const hasFile = 'file' in options; - const hasContent = 'content' in options; - if (!(hasFile || hasContent) || (hasFile && hasContent)) { - throw (0, errors_1.errorWithCode)(new Error('Either a file or content field is required for valid file upload. You cannot supply both'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + /** + * Generic method for calling a Web API method + * @param method - the Web API method to call {@link https://api.slack.com/methods} + * @param options - options + */ + apiCall(method, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + this.logger.debug(`apiCall('${method}') start`); + warnDeprecations(method, this.logger); + warnIfFallbackIsMissing(method, this.logger, options); + warnIfThreadTsIsNotString(method, this.logger, options); + if (typeof options === 'string' || typeof options === 'number' || typeof options === 'boolean') { + throw new TypeError(`Expected an options argument but instead received a ${typeof options}`); + } + (0, file_upload_1.warnIfNotUsingFilesUploadV2)(method, this.logger); + // @ts-expect-error insufficient overlap between Record and FilesUploadV2Arguments + if (method === 'files.uploadV2') + return this.filesUploadV2(options); + const headers = {}; + if (options.token) + headers.Authorization = `Bearer ${options.token}`; + const response = yield this.makeRequest(method, Object.assign({ team_id: this.teamId }, options), headers); + const result = yield this.buildResult(response); + this.logger.debug(`http request result: ${JSON.stringify(result)}`); + // log warnings in response metadata + if (result.response_metadata !== undefined && result.response_metadata.warnings !== undefined) { + result.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)); + } + // log warnings and errors in response metadata messages + // related to https://api.slack.com/changelog/2016-09-28-response-metadata-is-on-the-way + if (result.response_metadata !== undefined && result.response_metadata.messages !== undefined) { + for (const msg of result.response_metadata.messages) { + const errReg = /\[ERROR\](.*)/; + const warnReg = /\[WARN\](.*)/; + if (errReg.test(msg)) { + const errMatch = msg.match(errReg); + if (errMatch != null) { + this.logger.error(errMatch[1].trim()); + } + } + else if (warnReg.test(msg)) { + const warnMatch = msg.match(warnReg); + if (warnMatch != null) { + this.logger.warn(warnMatch[1].trim()); + } + } + } + } + // If result's content is gzip, "ok" property is not returned with successful response + // TODO: look into simplifying this code block to only check for the second condition + // if an { ok: false } body applies for all API errors + if (!result.ok && response.headers['content-type'] !== 'application/gzip') { + throw (0, errors_1.platformErrorFromResult)(result); + } + if ('ok' in result && result.ok === false) { + throw (0, errors_1.platformErrorFromResult)(result); + } + this.logger.debug(`apiCall('${method}') end`); + return result; + }); } - if ('file' in options) { - const { file } = options; - if (file && !(typeof file === 'string' || Buffer.isBuffer(file) || file instanceof node_stream_1.Readable)) { - throw (0, errors_1.errorWithCode)(new Error('file must be a valid string path, buffer or Readable'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + paginate(method, options, shouldStop, reduce) { + const pageSize = (() => { + if (options !== undefined && typeof options.limit === 'number') { + const { limit } = options; + options.limit = undefined; + return limit; + } + return defaultPageSize; + })(); + function generatePages() { + return __asyncGenerator(this, arguments, function* generatePages_1() { + // when result is undefined, that signals that the first of potentially many calls has not yet been made + let result; + // paginationOptions stores pagination options not already stored in the options argument + let paginationOptions = { + limit: pageSize, + }; + if (options !== undefined && options.cursor !== undefined) { + paginationOptions.cursor = options.cursor; + } + // NOTE: test for the situation where you're resuming a pagination using and existing cursor + while (result === undefined || paginationOptions !== undefined) { + result = yield __await(this.apiCall(method, Object.assign(options !== undefined ? options : {}, paginationOptions))); + yield yield __await(result); + paginationOptions = paginationOptionsForNextPage(result, pageSize); + } + }); } + if (shouldStop === undefined) { + return generatePages.call(this); + } + const pageReducer = reduce !== undefined ? reduce : noopPageReducer; + let index = 0; + return (() => __awaiter(this, void 0, void 0, function* () { + // Unroll the first iteration of the iterator + // This is done primarily because in order to satisfy the type system, we need a variable that is typed as A + // (shown as accumulator before), but before the first iteration all we have is a variable typed A | undefined. + // Unrolling the first iteration allows us to deal with undefined as a special case. + var _a, e_1, _b, _c; + const pageIterator = generatePages.call(this); + const firstIteratorResult = yield pageIterator.next(undefined); + // Assumption: there will always be at least one result in a paginated API request + // if (firstIteratorResult.done) { return; } + const firstPage = firstIteratorResult.value; + let accumulator = pageReducer(undefined, firstPage, index); + index += 1; + if (shouldStop(firstPage)) { + return accumulator; + } + try { + // Continue iteration + for (var _d = true, pageIterator_1 = __asyncValues(pageIterator), pageIterator_1_1; pageIterator_1_1 = yield pageIterator_1.next(), _a = pageIterator_1_1.done, !_a; _d = true) { + _c = pageIterator_1_1.value; + _d = false; + const page = _c; + accumulator = pageReducer(accumulator, page, index); + if (shouldStop(page)) { + return accumulator; + } + index += 1; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = pageIterator_1.return)) yield _b.call(pageIterator_1); + } + finally { if (e_1) throw e_1.error; } + } + return accumulator; + }))(); } - if ('content' in options && options.content && typeof options.content !== 'string') { - throw (0, errors_1.errorWithCode)(new Error('content must be a string'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } -} -exports.errorIfInvalidOrMissingFileData = errorIfInvalidOrMissingFileData; -/** - * @param options - * @param logger - * @returns filename if it exists - */ -function warnIfMissingOrInvalidFileNameAndDefault(options, logger) { - var _a; - const DEFAULT_FILETYPE = 'txt'; - const DEFAULT_FILENAME = `file.${(_a = options.filetype) !== null && _a !== void 0 ? _a : DEFAULT_FILETYPE}`; - const { filename } = options; - if (!filename) { - // Filename was an optional property in legacy method - logger.warn(buildMissingFileNameWarning()); - return DEFAULT_FILENAME; + /** + * This wrapper method provides an easy way to upload files using the following endpoints: + * + * **#1**: For each file submitted with this method, submit filenames + * and file metadata to {@link https://api.slack.com/methods/files.getUploadURLExternal files.getUploadURLExternal} to request a URL to + * which to send the file data to and an id for the file + * + * **#2**: for each returned file `upload_url`, upload corresponding file to + * URLs returned from step 1 (e.g. https://files.slack.com/upload/v1/...\") + * + * **#3**: Complete uploads {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} + * @param options + */ + filesUploadV2(options) { + return __awaiter(this, void 0, void 0, function* () { + this.logger.debug('files.uploadV2() start'); + // 1 + const fileUploads = yield this.getAllFileUploads(options); + const fileUploadsURLRes = yield this.fetchAllUploadURLExternal(fileUploads); + // set the upload_url and file_id returned from Slack + fileUploadsURLRes.forEach((res, idx) => { + fileUploads[idx].upload_url = res.upload_url; + fileUploads[idx].file_id = res.file_id; + }); + // 2 + yield this.postFileUploadsToExternalURL(fileUploads, options); + // 3 + const completion = yield this.completeFileUploads(fileUploads); + return { ok: true, files: completion }; + }); } - if (filename.split('.').length < 2) { - // likely filename is missing extension - logger.warn(buildMissingExtensionWarning(filename)); + /** + * For each file submitted with this method, submits filenames + * and file metadata to files.getUploadURLExternal to request a URL to + * which to send the file data to and an id for the file + * @param fileUploads + */ + fetchAllUploadURLExternal(fileUploads) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(fileUploads.map((upload) => { + const options = { + filename: upload.filename, + length: upload.length, + alt_text: upload.alt_text, + snippet_type: upload.snippet_type, + }; + if ('token' in upload) { + options.token = upload.token; + } + return this.files.getUploadURLExternal(options); + })); + }); } - return filename; -} -exports.warnIfMissingOrInvalidFileNameAndDefault = warnIfMissingOrInvalidFileNameAndDefault; -/** - * `filetype` param is no longer supported and will be ignored - * @param options - * @param logger - */ -function warnIfLegacyFileType(options, logger) { - if (options.filetype) { - logger.warn(buildLegacyFileTypeWarning()); + /** + * Complete uploads. + * @param fileUploads + * @returns + */ + completeFileUploads(fileUploads) { + return __awaiter(this, void 0, void 0, function* () { + const toComplete = Object.values((0, file_upload_1.getAllFileUploadsToComplete)(fileUploads)); + return Promise.all(toComplete.map((job) => this.files.completeUploadExternal(job))); + }); } -} -exports.warnIfLegacyFileType = warnIfLegacyFileType; -// Validation message utilities -function buildMissingFileIdError() { - return 'Missing required file id for file upload completion'; -} -exports.buildMissingFileIdError = buildMissingFileIdError; -function buildFileSizeErrorMsg() { - return 'There was an issue calculating the size of your file'; -} -exports.buildFileSizeErrorMsg = buildFileSizeErrorMsg; -function buildLegacyFileTypeWarning() { - return ('filetype is no longer a supported field in files.uploadV2.' + - ' \nPlease remove this field. To indicate file type, please do so via the required filename property' + - ' using the appropriate file extension, e.g. image.png, text.txt'); -} -exports.buildLegacyFileTypeWarning = buildLegacyFileTypeWarning; -function buildMissingFileNameWarning() { - return ('filename is a required field for files.uploadV2. \n For backwards compatibility and ease of migration, ' + - 'defaulting the filename. For best experience and consistent unfurl behavior, you' + - ' should set the filename property with correct file extension, e.g. image.png, text.txt'); -} -exports.buildMissingFileNameWarning = buildMissingFileNameWarning; -function buildMissingExtensionWarning(filename) { - return `filename supplied '${filename}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`; -} -exports.buildMissingExtensionWarning = buildMissingExtensionWarning; -function buildLegacyMethodWarning(method) { - return `${method} may cause some issues like timeouts for relatively large files.`; -} -exports.buildLegacyMethodWarning = buildLegacyMethodWarning; -function buildGeneralFilesUploadWarning() { - return ('Our latest recommendation is to use client.files.uploadV2() method, ' + - 'which is mostly compatible and much stabler, instead.'); -} -exports.buildGeneralFilesUploadWarning = buildGeneralFilesUploadWarning; -function buildFilesUploadMissingMessage() { - return 'Something went wrong with processing file_uploads'; -} -exports.buildFilesUploadMissingMessage = buildFilesUploadMissingMessage; -function buildChannelsWarning() { - return ("Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, " + - "we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."); -} -exports.buildChannelsWarning = buildChannelsWarning; -function buildMultipleChannelsErrorMsg() { - return 'Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead.'; -} -exports.buildMultipleChannelsErrorMsg = buildMultipleChannelsErrorMsg; -function buildInvalidFilesUploadParamError() { - return ('You may supply file_uploads only for a single channel, comment, thread respectively. ' + - 'Therefore, please supply any channel_id, initial_comment, thread_ts in the top-layer.'); -} -exports.buildInvalidFilesUploadParamError = buildInvalidFilesUploadParamError; -//# sourceMappingURL=file-upload.js.map - -/***/ }), - -/***/ 4060: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Build a Promise that will resolve after the specified number of milliseconds. - * @param ms milliseconds to wait - * @param value value for eventual resolution - */ -function delay(ms) { - return new Promise((resolve) => { - setTimeout(resolve, ms); - }); -} -exports["default"] = delay; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 5105: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/// -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + /** + * for each returned file upload URL, upload corresponding file + * @param fileUploads + * @returns + */ + postFileUploadsToExternalURL(fileUploads, options) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(fileUploads.map((upload) => __awaiter(this, void 0, void 0, function* () { + const { upload_url, file_id, filename, data } = upload; + // either file or content will be defined + const body = data; + // try to post to external url + if (upload_url) { + const headers = {}; + if (options.token) + headers.Authorization = `Bearer ${options.token}`; + const uploadRes = yield this.makeRequest(upload_url, { + body, + }, headers); + if (uploadRes.status !== 200) { + return Promise.reject(Error(`Failed to upload file (id:${file_id}, filename: ${filename})`)); + } + const returnData = { ok: true, body: uploadRes.data }; + return Promise.resolve(returnData); + } + return Promise.reject(Error(`No upload url found for file (id: ${file_id}, filename: ${filename}`)); + }))); + }); } - Object.defineProperty(o, k2, desc); -}) : (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); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.addAppMetadata = exports.retryPolicies = exports.ErrorCode = exports.LogLevel = exports.WebClientEvent = exports.WebClient = void 0; -var WebClient_1 = __nccwpck_require__(4048); -Object.defineProperty(exports, "WebClient", ({ enumerable: true, get: function () { return WebClient_1.WebClient; } })); -Object.defineProperty(exports, "WebClientEvent", ({ enumerable: true, get: function () { return WebClient_1.WebClientEvent; } })); -var logger_1 = __nccwpck_require__(4385); -Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return logger_1.LogLevel; } })); -var errors_1 = __nccwpck_require__(8486); -Object.defineProperty(exports, "ErrorCode", ({ enumerable: true, get: function () { return errors_1.ErrorCode; } })); -var retry_policies_1 = __nccwpck_require__(1766); -Object.defineProperty(exports, "retryPolicies", ({ enumerable: true, get: function () { return __importDefault(retry_policies_1).default; } })); -var instrument_1 = __nccwpck_require__(9224); -Object.defineProperty(exports, "addAppMetadata", ({ enumerable: true, get: function () { return instrument_1.addAppMetadata; } })); -__exportStar(__nccwpck_require__(9339), exports); -__exportStar(__nccwpck_require__(381), exports); -__exportStar(__nccwpck_require__(5591), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 9224: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + /** + * @param options All file uploads arguments + * @returns An array of file upload entries + */ + getAllFileUploads(options) { + return __awaiter(this, void 0, void 0, function* () { + let fileUploads = []; + // add single file data to uploads if file or content exists at the top level + if ('file' in options || 'content' in options) { + fileUploads.push(yield (0, file_upload_1.getFileUploadJob)(options, this.logger)); + } + // add multiple files data when file_uploads is supplied + if ('file_uploads' in options) { + fileUploads = fileUploads.concat(yield (0, file_upload_1.getMultipleFileUploadJobs)(options, this.logger)); + } + return fileUploads; + }); } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getUserAgent = exports.addAppMetadata = void 0; -const os = __importStar(__nccwpck_require__(8161)); -const node_path_1 = __nccwpck_require__(6760); -const packageJson = __nccwpck_require__(6734); -/** - * Replaces occurrences of '/' with ':' in a string, since '/' is meaningful inside User-Agent strings as a separator. - */ -function replaceSlashes(s) { - return s.replace('/', ':'); -} -// TODO: for the deno build (see the `npm run build:deno` npm run script), we could replace the `os-browserify` npm -// module shim with our own shim leveraging the deno beta compatibility layer for node's `os` module (for more info -// see https://deno.land/std@0.116.0/node/os.ts). At the time of writing this TODO (2021/11/25), this required deno -// v1.16.2 and use of the --unstable flag. Once support for this exists without the --unstable flag, we can improve -// the `os` module deno shim to correctly report operating system from a deno runtime. Until then, the below `os`- -// based code will report "browser/undefined" from a deno runtime. -const baseUserAgent = `${replaceSlashes(packageJson.name)}/${packageJson.version} ` + - `${(0, node_path_1.basename)(process.title)}/${process.version.replace('v', '')} ` + - `${os.platform()}/${os.release()}`; -const appMetadata = {}; + /** + * Low-level function to make a single API request. handles queuing, retries, and http-level errors + */ + makeRequest(url, body, headers = {}) { + return __awaiter(this, void 0, void 0, function* () { + // TODO: better input types - remove any + const task = () => this.requestQueue.add(() => __awaiter(this, void 0, void 0, function* () { + const requestURL = url.startsWith('https' || 0) ? url : `${this.axios.getUri() + url}`; + try { + // biome-ignore lint/suspicious/noExplicitAny: TODO: type this + const config = Object.assign({ headers }, this.tlsConfig); + // admin.analytics.getFile returns a binary response + // To be able to parse it, it should be read as an ArrayBuffer + if (url.endsWith('admin.analytics.getFile')) { + config.responseType = 'arraybuffer'; + } + // apps.event.authorizations.list will reject HTTP requests that send token in the body + // TODO: consider applying this change to all methods - though that will require thorough integration testing + if (url.endsWith('apps.event.authorizations.list')) { + body.token = undefined; + } + this.logger.debug(`http request url: ${requestURL}`); + this.logger.debug(`http request body: ${JSON.stringify(redact(body))}`); + // compile all headers - some set by default under the hood by axios - that will be sent along + let allHeaders = Object.keys(this.axios.defaults.headers).reduce((acc, cur) => { + if (!axiosHeaderPropsToIgnore.includes(cur)) { + acc[cur] = this.axios.defaults.headers[cur]; + } + return acc; + }, {}); + allHeaders = Object.assign(Object.assign(Object.assign({}, this.axios.defaults.headers.common), allHeaders), headers); + this.logger.debug(`http request headers: ${JSON.stringify(redact(allHeaders))}`); + const response = yield this.axios.post(url, body, config); + this.logger.debug('http response received'); + if (response.status === 429) { + const retrySec = parseRetryHeaders(response); + if (retrySec !== undefined) { + this.emit(WebClientEvent.RATE_LIMITED, retrySec, { url, body }); + if (this.rejectRateLimitedCalls) { + throw new p_retry_1.AbortError((0, errors_1.rateLimitedErrorWithDelay)(retrySec)); + } + this.logger.info(`API Call failed due to rate limiting. Will retry in ${retrySec} seconds.`); + // pause the request queue and then delay the rejection by the amount of time in the retry header + this.requestQueue.pause(); + // NOTE: if there was a way to introspect the current RetryOperation and know what the next timeout + // would be, then we could subtract that time from the following delay, knowing that it the next + // attempt still wouldn't occur until after the rate-limit header has specified. an even better + // solution would be to subtract the time from only the timeout of this next attempt of the + // RetryOperation. this would result in the staying paused for the entire duration specified in the + // header, yet this operation not having to pay the timeout cost in addition to that. + yield (0, helpers_1.default)(retrySec * 1000); + // resume the request queue and throw a non-abort error to signal a retry + this.requestQueue.start(); + // TODO: We may want to have more detailed info such as team_id, params except tokens, and so on. + throw new Error(`A rate limit was exceeded (url: ${url}, retry-after: ${retrySec})`); + } + // TODO: turn this into some CodedError + throw new p_retry_1.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${url}, retry-after header: ${response.headers['retry-after']})`)); + } + // Slack's Web API doesn't use meaningful status codes besides 429 and 200 + if (response.status !== 200) { + throw (0, errors_1.httpErrorFromResponse)(response); + } + return response; + } + catch (error) { + // To make this compatible with tsd, casting here instead of `catch (error: any)` + // biome-ignore lint/suspicious/noExplicitAny: errors can be anything + const e = error; + this.logger.warn('http request failed', e.message); + if (e.request) { + throw (0, errors_1.requestErrorWithOriginal)(e, this.attachOriginalToWebAPIRequestError); + } + throw error; + } + })); + // biome-ignore lint/suspicious/noExplicitAny: http responses can be anything + return (0, p_retry_1.default)(task, this.retryConfig); + }); + } + /** + * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either + * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used + * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type + * multipart/form-data. + * @param options - arguments for the Web API method + * @param headers - a mutable object representing the HTTP headers for the outgoing request + */ + serializeApiCallOptions(options, headers) { + // The following operation both flattens complex objects into a JSON-encoded strings and searches the values for + // binary content + let containsBinaryData = false; + // biome-ignore lint/suspicious/noExplicitAny: call options can be anything + const flattened = Object.entries(options).map(([key, value]) => { + if (value === undefined || value === null) { + return []; + } + let serializedValue = value; + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + containsBinaryData = true; + } + else if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') { + // if value is anything other than string, number, boolean, binary data, a Stream, or a Buffer, then encode it + // as a JSON string. + serializedValue = JSON.stringify(value); + } + return [key, serializedValue]; + }); + // A body with binary content should be serialized as multipart/form-data + if (containsBinaryData) { + this.logger.debug('Request arguments contain binary data'); + const form = flattened.reduce((frm, [key, value]) => { + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + const opts = {}; + opts.filename = (() => { + // attempt to find filename from `value`. adapted from: + // https://github.com/form-data/form-data/blob/028c21e0f93c5fefa46a7bbf1ba753e4f627ab7a/lib/form_data.js#L227-L230 + // formidable and the browser add a name property + // fs- and request- streams have path property + // biome-ignore lint/suspicious/noExplicitAny: form values can be anything + const streamOrBuffer = value; + if (typeof streamOrBuffer.name === 'string') { + return (0, node_path_1.basename)(streamOrBuffer.name); + } + if (typeof streamOrBuffer.path === 'string') { + return (0, node_path_1.basename)(streamOrBuffer.path); + } + return defaultFilename; + })(); + frm.append(key, value, opts); + } + else if (key !== undefined && value !== undefined) { + frm.append(key, value); + } + return frm; + }, new form_data_1.default()); + if (headers) { + // Copying FormData-generated headers into headers param + // not reassigning to headers param since it is passed by reference and behaves as an inout param + for (const [header, value] of Object.entries(form.getHeaders())) { + headers[header] = value; + } + } + return form; + } + // Otherwise, a simple key-value object is returned + if (headers) + headers['Content-Type'] = 'application/x-www-form-urlencoded'; + // biome-ignore lint/suspicious/noExplicitAny: form values can be anything + const initialValue = {}; + return (0, node_querystring_1.stringify)(flattened.reduce((accumulator, [key, value]) => { + if (key !== undefined && value !== undefined) { + accumulator[key] = value; + } + return accumulator; + }, initialValue)); + } + /** + * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevant + * HTTP headers into the object. + * @param response - an http response + */ + buildResult(response) { + return __awaiter(this, void 0, void 0, function* () { + let { data } = response; + const isGzipResponse = response.headers['content-type'] === 'application/gzip'; + // Check for GZIP response - if so, it is a successful response from admin.analytics.getFile + if (isGzipResponse) { + // admin.analytics.getFile will return a Buffer that can be unzipped + try { + const unzippedData = yield new Promise((resolve, reject) => { + node_zlib_1.default.unzip(data, (err, buf) => { + if (err) { + return reject(err); + } + return resolve(buf.toString().split('\n')); + }); + }) + .then((res) => res) + .catch((err) => { + throw err; + }); + const fileData = []; + if (Array.isArray(unzippedData)) { + for (const dataset of unzippedData) { + if (dataset && dataset.length > 0) { + fileData.push(JSON.parse(dataset)); + } + } + } + data = { file_data: fileData }; + } + catch (err) { + data = { ok: false, error: err }; + } + } + else if (!isGzipResponse && response.request.path === '/api/admin.analytics.getFile') { + // if it isn't a Gzip response but is from the admin.analytics.getFile request, + // decode the ArrayBuffer to JSON read the error + data = JSON.parse(new node_util_1.TextDecoder().decode(data)); + } + if (typeof data === 'string') { + // response.data can be a string, not an object for some reason + try { + data = JSON.parse(data); + } + catch (_) { + // failed to parse the string value as JSON data + data = { ok: false, error: data }; + } + } + if (data.response_metadata === undefined) { + data.response_metadata = {}; + } + // add scopes metadata from headers + if (response.headers['x-oauth-scopes'] !== undefined) { + data.response_metadata.scopes = response.headers['x-oauth-scopes'].trim().split(/\s*,\s*/); + } + if (response.headers['x-accepted-oauth-scopes'] !== undefined) { + data.response_metadata.acceptedScopes = response.headers['x-accepted-oauth-scopes'] + .trim() + .split(/\s*,\s*/); + } + // add retry metadata from headers + const retrySec = parseRetryHeaders(response); + if (retrySec !== undefined) { + data.response_metadata.retryAfter = retrySec; + } + return data; + }); + } +} +exports.WebClient = WebClient; /** - * Appends the app metadata into the User-Agent value - * @param appMetadata.name - name of tool to be counted in instrumentation - * @param appMetadata.version - version of tool to be counted in instrumentation + * The name used to prefix all logging generated from this object */ -function addAppMetadata({ name, version }) { - appMetadata[replaceSlashes(name)] = version; -} -exports.addAppMetadata = addAppMetadata; +WebClient.loggerName = 'WebClient'; +exports["default"] = WebClient; /** - * Returns the current User-Agent value for instrumentation + * Determines an appropriate set of cursor pagination options for the next request to a paginated API method. + * @param previousResult - the result of the last request, where the next cursor might be found. + * @param pageSize - the maximum number of additional items to fetch in the next request. */ -function getUserAgent() { - const appIdentifier = Object.entries(appMetadata) - .map(([name, version]) => `${name}/${version}`) - .join(' '); - // only prepend the appIdentifier when its not empty - return (appIdentifier.length > 0 ? `${appIdentifier} ` : '') + baseUserAgent; -} -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=instrument.js.map - -/***/ }), - -/***/ 4385: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getLogger = exports.LogLevel = void 0; -const logger_1 = __nccwpck_require__(9234); -var logger_2 = __nccwpck_require__(9234); -Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return logger_2.LogLevel; } })); -let instanceCount = 0; +function paginationOptionsForNextPage(previousResult, pageSize) { + if (previousResult !== undefined && + previousResult.response_metadata !== undefined && + previousResult.response_metadata.next_cursor !== undefined && + previousResult.response_metadata.next_cursor !== '') { + return { + limit: pageSize, + cursor: previousResult.response_metadata.next_cursor, + }; + } + return undefined; +} /** - * INTERNAL interface for getting or creating a named Logger. + * Extract the amount of time (in seconds) the platform has recommended this client wait before sending another request + * from a rate-limited HTTP response (statusCode = 429). */ -function getLogger(name, level, existingLogger) { - // Get a unique ID for the logger. - const instanceId = instanceCount; - instanceCount += 1; - // Set up the logger. - const logger = (() => { - if (existingLogger !== undefined) { - return existingLogger; +function parseRetryHeaders(response) { + if (response.headers['retry-after'] !== undefined) { + const retryAfter = Number.parseInt(response.headers['retry-after'], 10); + if (!Number.isNaN(retryAfter)) { + return retryAfter; } - return new logger_1.ConsoleLogger(); - })(); - logger.setName(`web-api:${name}:${instanceId}`); - if (level !== undefined) { - logger.setLevel(level); } - return logger; + return undefined; } -exports.getLogger = getLogger; -//# sourceMappingURL=logger.js.map +/** + * Log a warning when using a deprecated method + * @param method api method being called + * @param logger instance of web clients logger + */ +function warnDeprecations(method, logger) { + const deprecatedMethods = ['workflows.']; + const isDeprecated = deprecatedMethods.some((depMethod) => { + const re = new RegExp(`^${depMethod}`); + return re.test(method); + }); + if (isDeprecated) { + logger.warn(`${method} is deprecated. Please check on https://api.slack.com/methods for an alternative.`); + } +} +/** + * Log a warning when using chat.postMessage without text argument or attachments with fallback argument + * @param method api method being called + * @param logger instance of we clients logger + * @param options arguments for the Web API method + */ +function warnIfFallbackIsMissing(method, logger, options) { + const targetMethods = ['chat.postEphemeral', 'chat.postMessage', 'chat.scheduleMessage']; + const isTargetMethod = targetMethods.includes(method); + const hasAttachments = (args) => Array.isArray(args.attachments) && args.attachments.length; + const missingAttachmentFallbackDetected = (args) => Array.isArray(args.attachments) && + args.attachments.some((attachment) => !attachment.fallback || attachment.fallback.trim() === ''); + const isEmptyText = (args) => args.text === undefined || args.text === null || args.text === ''; + const buildMissingTextWarning = () => `The top-level \`text\` argument is missing in the request payload for a ${method} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`; + const buildMissingFallbackWarning = () => `Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${method} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://api.slack.com/reference/messaging/attachments#legacy_fields for more details).`; + if (isTargetMethod && typeof options === 'object') { + if (hasAttachments(options)) { + if (missingAttachmentFallbackDetected(options) && isEmptyText(options)) { + logger.warn(buildMissingTextWarning()); + logger.warn(buildMissingFallbackWarning()); + } + } + else if (isEmptyText(options)) { + logger.warn(buildMissingTextWarning()); + } + } +} +/** + * Log a warning when thread_ts is not a string + * @param method api method being called + * @param logger instance of web clients logger + * @param options arguments for the Web API method + */ +function warnIfThreadTsIsNotString(method, logger, options) { + const targetMethods = ['chat.postEphemeral', 'chat.postMessage', 'chat.scheduleMessage', 'files.upload']; + const isTargetMethod = targetMethods.includes(method); + if (isTargetMethod && (options === null || options === void 0 ? void 0 : options.thread_ts) !== undefined && typeof (options === null || options === void 0 ? void 0 : options.thread_ts) !== 'string') { + logger.warn(buildThreadTsWarningMessage(method)); + } +} +function buildThreadTsWarningMessage(method) { + return `The given thread_ts value in the request payload for a ${method} call is a float value. We highly recommend using a string value instead.`; +} +exports.buildThreadTsWarningMessage = buildThreadTsWarningMessage; +/** + * Takes an object and redacts specific items + * @param body + * @returns + */ +function redact(body) { + // biome-ignore lint/suspicious/noExplicitAny: objects can be anything + const flattened = Object.entries(body).map(([key, value]) => { + // no value provided + if (value === undefined || value === null) { + return []; + } + let serializedValue = value; + // redact possible tokens + if (key.match(/.*token.*/) !== null || key.match(/[Aa]uthorization/)) { + serializedValue = '[[REDACTED]]'; + } + // when value is buffer or stream we can avoid logging it + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + serializedValue = '[[BINARY VALUE OMITTED]]'; + } + else if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') { + serializedValue = JSON.stringify(value); + } + return [key, serializedValue]; + }); + // return as object + const initialValue = {}; + return flattened.reduce((accumulator, [key, value]) => { + if (key !== undefined && value !== undefined) { + accumulator[key] = value; + } + return accumulator; + }, initialValue); +} +//# sourceMappingURL=WebClient.js.map /***/ }), -/***/ 9339: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 8486: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Methods = void 0; -const eventemitter3_1 = __nccwpck_require__(2415); -const WebClient_1 = __nccwpck_require__(4048); +exports.rateLimitedErrorWithDelay = exports.platformErrorFromResult = exports.httpErrorFromResponse = exports.requestErrorWithOriginal = exports.errorWithCode = exports.ErrorCode = void 0; /** - * Binds a certain `method` and its (required) arguments and result types to the `apiCall` method in `WebClient`. + * A dictionary of codes for errors produced by this package */ -function bindApiCall(self, method) { - const apiMethod = self.apiCall.bind(self, method); - return apiMethod; +var ErrorCode; +(function (ErrorCode) { + // general error + ErrorCode["RequestError"] = "slack_webapi_request_error"; + ErrorCode["HTTPError"] = "slack_webapi_http_error"; + ErrorCode["PlatformError"] = "slack_webapi_platform_error"; + ErrorCode["RateLimitedError"] = "slack_webapi_rate_limited_error"; + // file uploads errors + ErrorCode["FileUploadInvalidArgumentsError"] = "slack_webapi_file_upload_invalid_args_error"; + ErrorCode["FileUploadReadFileDataError"] = "slack_webapi_file_upload_read_file_data_error"; +})(ErrorCode || (exports.ErrorCode = ErrorCode = {})); +/** + * Factory for producing a {@link CodedError} from a generic error + */ +function errorWithCode(error, code) { + // NOTE: might be able to return something more specific than a CodedError with conditional typing + const codedError = error; + codedError.code = code; + return codedError; } +exports.errorWithCode = errorWithCode; /** - * Binds a certain `method` and its (required) arguments and result types to the `apiCall` method in `WebClient`. + * A factory to create WebAPIRequestError objects + * @param original - original error + * @param attachOriginal - config indicating if 'original' property should be added on the error object */ -function bindApiCallWithOptionalArgument(self, method) { - const apiMethod = self.apiCall.bind(self, method); - return apiMethod; +function requestErrorWithOriginal(original, attachOriginal) { + const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError); + if (attachOriginal) { + error.original = original; + } + return error; } -function bindFilesUploadV2(self) { - return self.filesUploadV2.bind(self); +exports.requestErrorWithOriginal = requestErrorWithOriginal; +/** + * A factory to create WebAPIHTTPError objects + * @param response - original error + */ +function httpErrorFromResponse(response) { + const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError); + error.statusCode = response.status; + error.statusMessage = response.statusText; + const nonNullHeaders = {}; + for (const k of Object.keys(response.headers)) { + if (k && response.headers[k]) { + nonNullHeaders[k] = response.headers[k]; + } + } + error.headers = nonNullHeaders; + error.body = response.data; + return error; } +exports.httpErrorFromResponse = httpErrorFromResponse; /** - * A class that defines all Web API methods, their arguments type, their response type, and binds those methods to the - * `apiCall` class method. + * A factory to create WebAPIPlatformError objects + * @param result - Web API call result */ -class Methods extends eventemitter3_1.EventEmitter { - constructor() { - super(); - this.admin = { - analytics: { - /** - * @description Retrieve analytics data for a given date, presented as a compressed JSON file. - * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. - */ - getFile: bindApiCall(this, 'admin.analytics.getFile'), - }, - apps: { - activities: { - /** - * @description Get logs for a specified team/org. - * @see {@link https://api.slack.com/methods/admin.apps.activities.list `admin.apps.activities.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'admin.apps.activities.list'), - }, - /** - * @description Approve an app for installation on a workspace. - * @see {@link https://api.slack.com/methods/admin.apps.approve `admin.apps.approve` API reference}. - */ - approve: bindApiCall(this, 'admin.apps.approve'), - approved: { - /** - * @description List approved apps for an org or workspace. - * @see {@link https://api.slack.com/methods/admin.apps.approved.list `admin.apps.approved.list` API reference}. - */ - list: bindApiCall(this, 'admin.apps.approved.list'), - }, - /** - * @description Clear an app resolution. - * @see {@link https://api.slack.com/methods/admin.apps.clearResolution `admin.apps.clearResolution` API reference}. - */ - clearResolution: bindApiCall(this, 'admin.apps.clearResolution'), - config: { - /** - * @description Look up the app config for connectors by their IDs. - * @see {@link https://api.slack.com/methods/admin.apps.config.lookup `admin.apps.config.lookup` API reference}. - */ - lookup: bindApiCall(this, 'admin.apps.config.lookup'), - /** - * @description Set the app config for a connector. - * @see {@link https://api.slack.com/methods/admin.apps.config.set `admin.apps.config.set` API reference}. - */ - set: bindApiCall(this, 'admin.apps.config.set'), - }, - requests: { - /** - * @description Cancel app request for team. - * @see {@link https://api.slack.com/methods/admin.apps.requests.cancel `admin.apps.requests.cancel` API reference}. - */ - cancel: bindApiCall(this, 'admin.apps.requests.cancel'), - /** - * @description List app requests for a team/workspace. - * @see {@link https://api.slack.com/methods/admin.apps.requests.list `admin.apps.requests.list` API reference}. - */ - list: bindApiCall(this, 'admin.apps.requests.list'), - }, - /** - * @description Restrict an app for installation on a workspace. - * @see {@link https://api.slack.com/methods/admin.apps.restrict `admin.apps.restrict` API reference}. - */ - restrict: bindApiCall(this, 'admin.apps.restrict'), - restricted: { - /** - * @description List restricted apps for an org or workspace. - * @see {@link https://api.slack.com/methods/admin.apps.restricted.list `admin.apps.restricted.list` API reference}. - */ - list: bindApiCall(this, 'admin.apps.restricted.list'), - }, - /** - * @description Uninstall an app from one or many workspaces, or an entire enterprise organization. - * @see {@link https://api.slack.com/methods/admin.apps.uninstall `admin.apps.uninstall` API reference}. - */ - uninstall: bindApiCall(this, 'admin.apps.uninstall'), - }, - auth: { - policy: { - /** - * @description Assign entities to a particular authentication policy. - * @see {@link https://api.slack.com/methods/admin.auth.policy.assignEntities `admin.auth.policy.assignEntities` API reference}. - */ - assignEntities: bindApiCall(this, 'admin.auth.policy.assignEntities'), - /** - * @description Fetch all the entities assigned to a particular authentication policy by name. - * @see {@link https://api.slack.com/methods/admin.auth.policy.getEntities `admin.auth.policy.getEntities` API reference}. - */ - getEntities: bindApiCall(this, 'admin.auth.policy.getEntities'), - /** - * @description Remove specified entities from a specified authentication policy. - * @see {@link https://api.slack.com/methods/admin.auth.policy.removeEntities `admin.auth.policy.removeEntities` API reference}. - */ - removeEntities: bindApiCall(this, 'admin.auth.policy.removeEntities'), - }, - }, - barriers: { - /** - * @description Create an Information Barrier. - * @see {@link https://api.slack.com/methods/admin.barriers.create `admin.barriers.create` API reference}. - */ - create: bindApiCall(this, 'admin.barriers.create'), - /** - * @description Delete an existing Information Barrier. - * @see {@link https://api.slack.com/methods/admin.barriers.delete `admin.barriers.delete` API reference}. - */ - delete: bindApiCall(this, 'admin.barriers.delete'), - /** - * @description Get all Information Barriers for your organization. - * @see {@link https://api.slack.com/methods/admin.barriers.list `admin.barriers.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'admin.barriers.list'), - /** - * @description Update an existing Information Barrier. - * @see {@link https://api.slack.com/methods/admin.barriers.update `admin.barriers.update` API reference}. - */ - update: bindApiCall(this, 'admin.barriers.update'), - }, - conversations: { - /** - * @description Archive a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.archive `admin.conversations.archive` API reference}. - */ - archive: bindApiCall(this, 'admin.conversations.archive'), - /** - * @description Archive public or private channels in bulk. - * @see {@link https://api.slack.com/methods/admin.conversations.bulkArchive `admin.conversations.bulkArchive` API reference}. - */ - bulkArchive: bindApiCall(this, 'admin.conversations.bulkArchive'), - /** - * @description Delete public or private channels in bulk. - * @see {@link https://api.slack.com/methods/admin.conversations.bulkDelet `admin.conversations.bulkDelete` API reference}. - */ - bulkDelete: bindApiCall(this, 'admin.conversations.bulkDelete'), - /** - * @description Move public or private channels in bulk. - * @see {@link https://api.slack.com/methods/admin.conversations.bulkMove `admin.conversations.bulkMove` API reference}. - */ - bulkMove: bindApiCall(this, 'admin.conversations.bulkMove'), - /** - * @description Convert a public channel to a private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.convertToPrivate `admin.conversations.convertToPrivate` API reference}. - */ - convertToPrivate: bindApiCall(this, 'admin.conversations.convertToPrivate'), - /** - * @description Convert a private channel to a public channel. - * @see {@link https://api.slack.com/methods/admin.conversations.convertToPublic `admin.conversations.convertToPublic` API reference}. - */ - convertToPublic: bindApiCall(this, 'admin.conversations.convertToPublic'), - /** - * @description Create a public or private channel-based conversation. - * @see {@link https://api.slack.com/methods/admin.conversations.create `admin.conversations.create` API reference}. - */ - create: bindApiCall(this, 'admin.conversations.create'), - /** - * @description Delete a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.delete `admin.conversations.delete` API reference}. - */ - delete: bindApiCall(this, 'admin.conversations.delete'), - /** - * @description Disconnect a connected channel from one or more workspaces. - * @see {@link https://api.slack.com/methods/admin.conversations.disconnectShared `admin.conversations.disconnectShared` API reference}. - */ - disconnectShared: bindApiCall(this, 'admin.conversations.disconnectShared'), - ekm: { - /** - * @description List all disconnected channels — i.e., channels that were once connected to other workspaces - * and then disconnected — and the corresponding original channel IDs for key revocation with EKM. - * @see {@link https://api.slack.com/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo `admin.conversations.ekm.listOriginalConnectedChannelInfo` API reference}. - */ - listOriginalConnectedChannelInfo: bindApiCallWithOptionalArgument(this, 'admin.conversations.ekm.listOriginalConnectedChannelInfo'), - }, - /** - * @description Get conversation preferences for a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.getConversationPrefs `admin.conversations.getConversationPrefs` API reference}. - */ - getConversationPrefs: bindApiCall(this, 'admin.conversations.getConversationPrefs'), - /** - * @description Get a conversation's retention policy. - * @see {@link https://api.slack.com/methods/admin.conversations.getCustomRetention `admin.conversations.getCustomRetention` API reference}. - */ - getCustomRetention: bindApiCall(this, 'admin.conversations.getCustomRetention'), - /** - * @description Get all the workspaces a given public or private channel is connected to within - * this Enterprise org. - * @see {@link https://api.slack.com/methods/admin.conversations.getTeams `admin.conversations.getTeams` API reference}. - */ - getTeams: bindApiCall(this, 'admin.conversations.getTeams'), - /** - * @description Invite a user to a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.invite `admin.conversations.invite` API reference}. - */ - invite: bindApiCall(this, 'admin.conversations.invite'), - /** - * @description Returns channels on the given team using the filters. - * @see {@link https://api.slack.com/methods/admin.conversations.lookup `admin.conversations.lookup` API reference}. - */ - lookup: bindApiCall(this, 'admin.conversations.lookup'), - /** - * @description Remove a conversation's retention policy. - * @see {@link https://api.slack.com/methods/admin.conversations.removeCustomRetention `admin.conversations.removeCustomRetention` API reference}. - */ - removeCustomRetention: bindApiCall(this, 'admin.conversations.removeCustomRetention'), - /** - * @description Rename a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.rename `admin.conversations.rename` API reference}. - */ - rename: bindApiCall(this, 'admin.conversations.rename'), - restrictAccess: { - /** - * @description Add an allowlist of IDP groups for accessing a channel. - * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.addGroup `admin.conversations.restrictAccess.addGroup` API reference}. - */ - addGroup: bindApiCall(this, 'admin.conversations.restrictAccess.addGroup'), - /** - * @description List all IDP Groups linked to a channel. - * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.listGroups `admin.conversations.restrictAccess.listGroups` API reference}. - */ - listGroups: bindApiCall(this, 'admin.conversations.restrictAccess.listGroups'), - /** - * @description Remove a linked IDP group linked from a private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.removeGroup `admin.conversations.restrictAccess.removeGroup` API reference}. - */ - removeGroup: bindApiCall(this, 'admin.conversations.restrictAccess.removeGroup'), - }, - /** - * @description Search for public or private channels in an Enterprise organization. - * @see {@link https://api.slack.com/methods/admin.conversations.search `admin.conversations.search` API reference}. - */ - search: bindApiCallWithOptionalArgument(this, 'admin.conversations.search'), - /** - * @description Set the posting permissions for a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.setConversationPrefs `admin.conversations.setConversationPrefs` API reference}. - */ - setConversationPrefs: bindApiCall(this, 'admin.conversations.setConversationPrefs'), - /** - * @description Set a conversation's retention policy. - * @see {@link https://api.slack.com/methods/admin.conversations.setCustomRetention `admin.conversations.setCustomRetention` API reference}. - */ - setCustomRetention: bindApiCall(this, 'admin.conversations.setCustomRetention'), - /** - * @description Set the workspaces in an Enterprise grid org that connect to a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.setTeams `admin.conversations.setTeams` API reference}. - */ - setTeams: bindApiCall(this, 'admin.conversations.setTeams'), - /** - * @description Unarchive a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.unarchive `admin.conversations.unarchive` API reference}. - */ - unarchive: bindApiCall(this, 'admin.conversations.unarchive'), - }, - emoji: { - /** - * @description Add an emoji. - * @see {@link https://api.slack.com/methods/admin.emoji.add `admin.emoji.add` API reference}. - */ - add: bindApiCall(this, 'admin.emoji.add'), - /** - * @description Add an emoji alias. - * @see {@link https://api.slack.com/methods/admin.emoji.addAlias `admin.emoji.addAlias` API reference}. - */ - addAlias: bindApiCall(this, 'admin.emoji.addAlias'), - /** - * @description List emoji for an Enterprise Grid organization. - * @see {@link https://api.slack.com/methods/admin.emoji.list `admin.emoji.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'admin.emoji.list'), - /** - * @description Remove an emoji across an Enterprise Grid organization. - * @see {@link https://api.slack.com/methods/admin.emoji.remove `admin.emoji.remove` API reference}. - */ - remove: bindApiCall(this, 'admin.emoji.remove'), - /** - * @description Rename an emoji. - * @see {@link https://api.slack.com/methods/admin.emoji.rename `admin.emoji.rename` API reference}. - */ - rename: bindApiCall(this, 'admin.emoji.rename'), - }, - functions: { - /** - * @description Look up functions by a set of apps. - * @see {@link https://api.slack.com/methods/admin.functions.list `admin.functions.list` API reference}. - */ - list: bindApiCall(this, 'admin.functions.list'), - permissions: { - /** - * @description Lookup the visibility of multiple Slack functions and include the users if - * it is limited to particular named entities. - * @see {@link https://api.slack.com/methods/admin.functions.permissions.lookup `admin.functions.permissions.lookup` API reference}. - */ - lookup: bindApiCall(this, 'admin.functions.permissions.lookup'), - /** - * @description Set the visibility of a Slack function and define the users or workspaces if - * it is set to named_entities. - * @see {@link https://api.slack.com/methods/admin.functions.permissions.set `admin.functions.permissions.set` API reference}. - */ - set: bindApiCall(this, 'admin.functions.permissions.set'), - }, - }, - inviteRequests: { - /** - * @description Approve a workspace invite request. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.approve `admin.inviteRequests.approve` API reference}. - */ - approve: bindApiCall(this, 'admin.inviteRequests.approve'), - approved: { - /** - * @description List all approved workspace invite requests. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.approved.list `admin.inviteRequests.approved.list` API reference}. - */ - list: bindApiCall(this, 'admin.inviteRequests.approved.list'), - }, - denied: { - /** - * @description List all denied workspace invite requests. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.denied.list `admin.inviteRequests.denied.list` API reference}. - */ - list: bindApiCall(this, 'admin.inviteRequests.denied.list'), - }, - /** - * @description Deny a workspace invite request. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.deny `admin.inviteRequests.deny` API reference}. - */ - deny: bindApiCall(this, 'admin.inviteRequests.deny'), - /** - * @description List all pending workspace invite requests. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.list `admin.inviteRequests.list` API reference}. - */ - list: bindApiCall(this, 'admin.inviteRequests.list'), - }, - roles: { - /** - * @description Adds members to the specified role with the specified scopes. - * @see {@link https://api.slack.com/methods/admin.roles.addAssignments `admin.roles.addAssignments` API reference}. - */ - addAssignments: bindApiCall(this, 'admin.roles.addAssignments'), - /** - * @description Lists assignments for all roles across entities. - * Options to scope results by any combination of roles or entities. - * @see {@link https://api.slack.com/methods/admin.roles.listAssignments `admin.roles.listAssignments` API reference}. - */ - listAssignments: bindApiCallWithOptionalArgument(this, 'admin.roles.listAssignments'), - /** - * @description Removes a set of users from a role for the given scopes and entities. - * @see {@link https://api.slack.com/methods/admin.roles.removeAssignments `admin.roles.removeAssignments` API reference}. - */ - removeAssignments: bindApiCall(this, 'admin.roles.removeAssignments'), - }, - teams: { - admins: { - /** - * @description List all of the admins on a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.admins.list `admin.teams.admins.list` API reference}. - */ - list: bindApiCall(this, 'admin.teams.admins.list'), - }, - /** - * @description Create an Enterprise team. - * @see {@link https://api.slack.com/methods/admin.teams.create `admin.teams.create` API reference}. - */ - create: bindApiCall(this, 'admin.teams.create'), - /** - * @description List all teams on an Enterprise organization. - * @see {@link https://api.slack.com/methods/admin.teams.list `admin.teams.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'admin.teams.list'), - owners: { - /** - * @description List all of the owners on a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. - */ - list: bindApiCall(this, 'admin.teams.owners.list'), - }, - settings: { - /** - * @description Fetch information about settings in a workspace. - * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. - */ - info: bindApiCall(this, 'admin.teams.settings.info'), - /** - * @description Set the default channels of a workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setDefaultChannels `admin.teams.settings.setDefaultChannels` API reference}. - */ - setDefaultChannels: bindApiCall(this, 'admin.teams.settings.setDefaultChannels'), - /** - * @description Set the description of a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setDescription `admin.teams.settings.setDescription` API reference}. - */ - setDescription: bindApiCall(this, 'admin.teams.settings.setDescription'), - /** - * @description Set the discoverability of a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setDiscoverability `admin.teams.settings.setDiscoverability` API reference}. - */ - setDiscoverability: bindApiCall(this, 'admin.teams.settings.setDiscoverability'), - /** - * @description Sets the icon of a workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setIcon `admin.teams.settings.setIcon` API reference}. - */ - setIcon: bindApiCall(this, 'admin.teams.settings.setIcon'), - /** - * @description Set the name of a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setName `admin.teams.settings.setName` API reference}. - */ - setName: bindApiCall(this, 'admin.teams.settings.setName'), - }, - }, - usergroups: { - /** - * @description Add up to one hundred default channels to an IDP group. - * @see {@link https://api.slack.com/methods/admin.usergroups.addChannels `admin.teams.usergroups.addChannels` API reference}. - */ - addChannels: bindApiCall(this, 'admin.usergroups.addChannels'), - /** - * @description Associate one or more default workspaces with an organization-wide IDP group. - * @see {@link https://api.slack.com/methods/admin.usergroups.addTeams `admin.teams.usergroups.addTeams` API reference}. - */ - addTeams: bindApiCall(this, 'admin.usergroups.addTeams'), - /** - * @description List the channels linked to an org-level IDP group (user group). - * @see {@link https://api.slack.com/methods/admin.usergroups.listChannels `admin.teams.usergroups.listChannels` API reference}. - */ - listChannels: bindApiCall(this, 'admin.usergroups.listChannels'), - /** - * @description Remove one or more default channels from an org-level IDP group (user group). - * @see {@link https://api.slack.com/methods/admin.usergroups.removeChannels `admin.teams.usergroups.removeChannels` API reference}. - */ - removeChannels: bindApiCall(this, 'admin.usergroups.removeChannels'), - }, - users: { - /** - * @description Add an Enterprise user to a workspace. - * @see {@link https://api.slack.com/methods/admin.users.assign `admin.users.assign` API reference}. - */ - assign: bindApiCall(this, 'admin.users.assign'), - /** - * @description Invite a user to a workspace. - * @see {@link https://api.slack.com/methods/admin.users.invite `admin.users.invite` API reference}. - */ - invite: bindApiCall(this, 'admin.users.invite'), - /** - * @description List users on a workspace. - * @see {@link https://api.slack.com/methods/admin.users.list `admin.users.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'admin.users.list'), - /** - * @description Remove a user from a workspace. - * @see {@link https://api.slack.com/methods/admin.users.remove `admin.users.remove` API reference}. - */ - remove: bindApiCall(this, 'admin.users.remove'), - session: { - /** - * @description Clear user-specific session settings—the session duration and what happens when the client - * closes—for a list of users. - * @see {@link https://api.slack.com/methods/admin.users.session.clearSettings `admin.users.session.clearSettings` API reference}. - */ - clearSettings: bindApiCall(this, 'admin.users.session.clearSettings'), - /** - * @description Get user-specific session settings—the session duration and what happens when the client - * closes—given a list of users. - * @see {@link https://api.slack.com/methods/admin.users.session.getSettings `admin.users.session.getSettings` API reference}. - */ - getSettings: bindApiCall(this, 'admin.users.session.getSettings'), - /** - * @description Revoke a single session for a user. The user will be forced to login to Slack. - * @see {@link https://api.slack.com/methods/admin.users.session.invalidate `admin.users.session.invalidate` API reference}. - */ - invalidate: bindApiCall(this, 'admin.users.session.invalidate'), - /** - * @description List active user sessions for an organization. - * @see {@link https://api.slack.com/methods/admin.users.session.list `admin.users.session.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'admin.users.session.list'), - /** - * @description Wipes all valid sessions on all devices for a given user. - * @see {@link https://api.slack.com/methods/admin.users.session.reset `admin.users.session.reset` API reference}. - */ - reset: bindApiCall(this, 'admin.users.session.reset'), - /** - * @description Enqueues an asynchronous job to wipe all valid sessions on all devices for a given user list. - * @see {@link https://api.slack.com/methods/admin.users.session.resetBulk `admin.users.session.resetBulk` API reference}. - */ - resetBulk: bindApiCall(this, 'admin.users.session.resetBulk'), - /** - * @description Configure the user-level session settings—the session duration and what happens when the client - * closes—for one or more users. - * @see {@link https://api.slack.com/methods/admin.users.session.setSettings `admin.users.session.setSettings` API reference}. - */ - setSettings: bindApiCall(this, 'admin.users.session.setSettings'), - }, - /** - * @description Set an existing guest, regular user, or owner to be an admin user. - * @see {@link https://api.slack.com/methods/admin.users.setAdmin `admin.users.setAdmin` API reference}. - */ - setAdmin: bindApiCall(this, 'admin.users.setAdmin'), - /** - * @description Set an expiration for a guest user. - * @see {@link https://api.slack.com/methods/admin.users.setExpiration `admin.users.setExpiration` API reference}. - */ - setExpiration: bindApiCall(this, 'admin.users.setExpiration'), - /** - * @description Set an existing guest, regular user, or admin user to be a workspace owner. - * @see {@link https://api.slack.com/methods/admin.users.setOwner `admin.users.setOwner` API reference}. - */ - setOwner: bindApiCall(this, 'admin.users.setOwner'), - /** - * @description Set an existing guest user, admin user, or owner to be a regular user. - * @see {@link https://api.slack.com/methods/admin.users.setRegular `admin.users.setRegular` API reference}. - */ - setRegular: bindApiCall(this, 'admin.users.setRegular'), - unsupportedVersions: { - /** - * @description Ask Slackbot to send you an export listing all workspace members using unsupported software, - * presented as a zipped CSV file. - * @see {@link https://api.slack.com/methods/admin.users.unsupportedVersions.export `admin.users.unsupportedVersions.export` API reference}. - */ - export: bindApiCall(this, 'admin.users.unsupportedVersions.export'), - }, - }, - workflows: { - collaborators: { - /** - * @description Add collaborators to workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.add `admin.workflows.collaborators.add` API reference}. - */ - add: bindApiCall(this, 'admin.workflows.collaborators.add'), - /** - * @description Remove collaborators from workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.remove `admin.workflows.collaborators.remove` API reference}. - */ - remove: bindApiCall(this, 'admin.workflows.collaborators.remove'), - }, - permissions: { - /** - * @description Look up the permissions for a set of workflows. - * @see {@link https://api.slack.com/methods/admin.workflows.permissions.lookup `admin.workflows.permissions.lookup` API reference}. - */ - lookup: bindApiCall(this, 'admin.workflows.permissions.lookup'), - }, - /** - * @description Search workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.search `admin.workflows.search` API reference}. - */ - search: bindApiCallWithOptionalArgument(this, 'admin.workflows.search'), - /** - * @description Unpublish workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.unpublish `admin.workflows.unpublish` API reference}. - */ - unpublish: bindApiCall(this, 'admin.workflows.unpublish'), - }, - }; - this.api = { - /** - * @description Checks API calling code. - * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. - */ - test: bindApiCallWithOptionalArgument(this, 'api.test'), - }; - this.assistant = { - threads: { - /** - * @description Set loading status to indicate that the app is building a response. - * @see {@link https://api.slack.com/methods/assistant.threads.setStatus `assistant.threads.setStatus` API reference}. - */ - setStatus: bindApiCall(this, 'assistant.threads.setStatus'), - /** - * @description Set suggested prompts for the user. Can suggest up to four prompts. - * @see {@link https://api.slack.com/methods/assistant.threads.setSuggestedPrompts `assistant.threads.setSuggestedPrompts` API reference}. - */ - setSuggestedPrompts: bindApiCall(this, 'assistant.threads.setSuggestedPrompts'), - /** - * @description Set the title of the thread. This is shown when a user views the app's chat history. - * @see {@link https://api.slack.com/methods/assistant.threads.setTitle `assistant.threads.setTitle` API reference}. - */ - setTitle: bindApiCall(this, 'assistant.threads.setTitle'), - }, - }; - this.apps = { - connections: { - /** - * @description Generate a temporary Socket Mode WebSocket URL that your app can connect to in order to receive - * events and interactive payloads over. - * @see {@link https://api.slack.com/methods/apps.connections.open `apps.connections.open` API reference}. - */ - open: bindApiCallWithOptionalArgument(this, 'apps.connections.open'), - }, - event: { - authorizations: { - /** - * @description Get a list of authorizations for the given event context. - * Each authorization represents an app installation that the event is visible to. - * @see {@link https://api.slack.com/methods/apps.event.authorizations.list `apps.event.authorizations.list` API reference}. - */ - list: bindApiCall(this, 'apps.event.authorizations.list'), - }, - }, - manifest: { - /** - * @description Create an app from an app manifest. - * @see {@link https://api.slack.com/methods/apps.manifest.create `apps.manifest.create` API reference}. - */ - create: bindApiCall(this, 'apps.manifest.create'), - /** - * @description Permanently deletes an app created through app manifests. - * @see {@link https://api.slack.com/methods/apps.manifest.delete `apps.manifest.delete` API reference}. - */ - delete: bindApiCall(this, 'apps.manifest.delete'), - /** - * @description Export an app manifest from an existing app. - * @see {@link https://api.slack.com/methods/apps.manifest.export `apps.manifest.export` API reference}. - */ - export: bindApiCall(this, 'apps.manifest.export'), - /** - * @description Update an app from an app manifest. - * @see {@link https://api.slack.com/methods/apps.manifest.update `apps.manifest.update` API reference}. - */ - update: bindApiCall(this, 'apps.manifest.update'), - /** - * @description Validate an app manifest. - * @see {@link https://api.slack.com/methods/apps.manifest.validate `apps.manifest.validate` API reference}. - */ - validate: bindApiCall(this, 'apps.manifest.validate'), - }, - /** - * @description Uninstalls your app from a workspace. - * @see {@link https://api.slack.com/methods/apps.uninstall `apps.uninstall` API reference}. - */ - uninstall: bindApiCall(this, 'apps.uninstall'), - }; - this.auth = { - /** - * @description Revokes a token. - * @see {@link https://api.slack.com/methods/auth.revoke `auth.revoke` API reference}. - */ - revoke: bindApiCallWithOptionalArgument(this, 'auth.revoke'), - teams: { - /** - * @description Obtain a full list of workspaces your org-wide app has been approved for. - * @see {@link https://api.slack.com/methods/auth.teams.list `auth.teams.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'auth.teams.list'), - }, - test: bindApiCallWithOptionalArgument(this, 'auth.test'), - }; - this.bookmarks = { - /** - * @description Add bookmark to a channel. - * @see {@link https://api.slack.com/methods/bookmarks.add `bookmarks.add` API reference}. - */ - add: bindApiCall(this, 'bookmarks.add'), - /** - * @description Edit bookmark. - * @see {@link https://api.slack.com/methods/bookmarks.edit `bookmarks.edit` API reference}. - */ - edit: bindApiCall(this, 'bookmarks.edit'), - /** - * @description List bookmarks for a channel. - * @see {@link https://api.slack.com/methods/bookmarks.list `bookmarks.list` API reference}. - */ - list: bindApiCall(this, 'bookmarks.list'), - /** - * @description Remove bookmark from a channel. - * @see {@link https://api.slack.com/methods/bookmarks.remove `bookmarks.remove` API reference}. - */ - remove: bindApiCall(this, 'bookmarks.remove'), - }; - this.bots = { - /** - * @description Gets information about a bot user. - * @see {@link https://api.slack.com/methods/bots.info `bots.info` API reference}. - */ - info: bindApiCallWithOptionalArgument(this, 'bots.info'), - }; - this.calls = { - /** - * @description Registers a new Call. - * @see {@link https://api.slack.com/methods/calls.add `calls.add` API reference}. - */ - add: bindApiCall(this, 'calls.add'), - /** - * @description Ends a Call. - * @see {@link https://api.slack.com/methods/calls.end `calls.end` API reference}. - */ - end: bindApiCall(this, 'calls.end'), - /** - * @description Returns information about a Call. - * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. - */ - info: bindApiCall(this, 'calls.info'), - /** - * @description Updates information about a Call. - * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. - */ - update: bindApiCall(this, 'calls.update'), - participants: { - /** - * @description Registers new participants added to a Call. - * @see {@link https://api.slack.com/methods/calls.participants.add `calls.participants.add` API reference}. - */ - add: bindApiCall(this, 'calls.participants.add'), - remove: bindApiCall(this, 'calls.participants.remove'), - }, - }; - this.canvases = { - access: { - /** - * @description Remove access to a canvas for specified entities. - * @see {@link https://api.slack.com/methods/canvases.access.delete `canvases.access.delete` API reference}. - */ - delete: bindApiCall(this, 'canvases.access.delete'), - /** - * @description Sets the access level to a canvas for specified entities. - * @see {@link https://api.slack.com/methods/canvases.access.set `canvases.access.set` API reference}. - */ - set: bindApiCall(this, 'canvases.access.set'), - }, - /** - * @description Create Canvas for a user. - * @see {@link https://api.slack.com/methods/canvases.create `canvases.create` API reference}. - */ - create: bindApiCallWithOptionalArgument(this, 'canvases.create'), - /** - * @description Deletes a canvas. - * @see {@link https://api.slack.com/methods/canvases.delete `canvases.delete` API reference}. - */ - delete: bindApiCall(this, 'canvases.delete'), - /** - * @description Update an existing canvas. - * @see {@link https://api.slack.com/methods/canvases.edit `canvases.edit` API reference}. - */ - edit: bindApiCall(this, 'canvases.edit'), - sections: { - /** - * @description Find sections matching the provided criteria. - * @see {@link https://api.slack.com/methods/canvases.sections.lookup `canvases.sections.lookup` API reference}. - */ - lookup: bindApiCall(this, 'canvases.sections.lookup'), - }, - }; - this.chat = { - /** - * @description Deletes a message. - * @see {@link https://api.slack.com/methods/chat.delete `chat.delete` API reference}. - */ - delete: bindApiCall(this, 'chat.delete'), - /** - * @description Deletes a pending scheduled message from the queue. - * @see {@link https://api.slack.com/methods/chat.deleteScheduledMessage `chat.deleteScheduledMessage` API reference}. - */ - deleteScheduledMessage: bindApiCall(this, 'chat.deleteScheduledMessage'), - /** - * @description Retrieve a permalink URL for a specific extant message. - * @see {@link https://api.slack.com/methods/chat.getPermalink `chat.getPermalink` API reference}. - */ - getPermalink: bindApiCall(this, 'chat.getPermalink'), - /** - * @description Share a me message into a channel. - * @see {@link https://api.slack.com/methods/chat.meMessage `chat.meMessage` API reference}. - */ - meMessage: bindApiCall(this, 'chat.meMessage'), - /** - * @description Sends an ephemeral message to a user in a channel. - * @see {@link https://api.slack.com/methods/chat.postEphemeral `chat.postEphemeral` API reference}. - */ - postEphemeral: bindApiCall(this, 'chat.postEphemeral'), - /** - * @description Sends a message to a channel. - * @see {@link https://api.slack.com/methods/chat.postMessage `chat.postMessage` API reference}. - */ - postMessage: bindApiCall(this, 'chat.postMessage'), - /** - * @description Schedules a message to be sent to a channel. - * @see {@link https://api.slack.com/methods/chat.scheduleMessage `chat.scheduleMessage` API reference}. - */ - scheduleMessage: bindApiCall(this, 'chat.scheduleMessage'), - scheduledMessages: { - /** - * @description Returns a list of scheduled messages. - * @see {@link https://api.slack.com/methods/chat.scheduledMessages.list `chat.scheduledMessages.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'chat.scheduledMessages.list'), - }, - /** - * @description Provide custom unfurl behavior for user-posted URLs. - * @see {@link https://api.slack.com/methods/chat.unfurl `chat.unfurl` API reference}. - */ - unfurl: bindApiCall(this, 'chat.unfurl'), - /** - * @description Updates a message. - * @see {@link https://api.slack.com/methods/chat.update `chat.update` API reference}. - */ - update: bindApiCall(this, 'chat.update'), - }; - this.conversations = { - /** - * @description Accepts an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.acceptSharedInvite `conversations.acceptSharedInvite` API reference}. - */ - acceptSharedInvite: bindApiCall(this, 'conversations.acceptSharedInvite'), - /** - * @description Approves an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.approveSharedInvite `conversations.approveSharedInvite` API reference}. - */ - approveSharedInvite: bindApiCall(this, 'conversations.approveSharedInvite'), - /** - * @description Archives a conversation. - * @see {@link https://api.slack.com/methods/conversations.archive `conversations.archive` API reference}. - */ - archive: bindApiCall(this, 'conversations.archive'), - canvases: { - /** - * @description Create a Channel Canvas for a channel. - * @see {@link https://api.slack.com/methods/conversations.canvases.create `conversations.canvases.create` API reference}. - */ - create: bindApiCall(this, 'conversations.canvases.create'), - }, - /** - * @description Closes a direct message or multi-person direct message. - * @see {@link https://api.slack.com/methods/conversations.close `conversations.close` API reference}. - */ - close: bindApiCall(this, 'conversations.close'), - /** - * @description Initiates a public or private channel-based conversation. - * @see {@link https://api.slack.com/methods/conversations.create `conversations.create` API reference}. - */ - create: bindApiCall(this, 'conversations.create'), - /** - * @description Declines an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.declineSharedInvite `conversations.declineSharedInvite` API reference}. - */ - declineSharedInvite: bindApiCall(this, 'conversations.declineSharedInvite'), - externalInvitePermissions: { - /** - * @description Convert a team in a shared channel from an External Limited channel to a fully shared Slack - * Connect channel or vice versa. - * @see {@link https://api.slack.com/methods/conversations.externalInvitePermissions.set `conversations.externalInvitePermissions.set` API reference}. - */ - set: bindApiCall(this, 'conversations.externalInvitePermissions.set'), - }, - /** - * @description Fetches a conversation's history of messages and events. - * @see {@link https://api.slack.com/methods/conversations.history `conversations.history` API reference}. - */ - history: bindApiCall(this, 'conversations.history'), - /** - * @description Retrieve information about a conversation. - * @see {@link https://api.slack.com/methods/conversations.info `conversations.info` API reference}. - */ - info: bindApiCall(this, 'conversations.info'), - /** - * @description Invites users to a channel. - * @see {@link https://api.slack.com/methods/conversations.invite `conversations.invite` API reference}. - */ - invite: bindApiCall(this, 'conversations.invite'), - /** - * @description Sends an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.inviteShared `conversations.inviteShared` API reference}. - */ - inviteShared: bindApiCall(this, 'conversations.inviteShared'), - /** - * @description Joins an existing conversation. - * @see {@link https://api.slack.com/methods/conversations.join `conversations.join` API reference}. - */ - join: bindApiCall(this, 'conversations.join'), - /** - * @description Removes a user from a conversation. - * @see {@link https://api.slack.com/methods/conversations.kick `conversations.kick` API reference}. - */ - kick: bindApiCall(this, 'conversations.kick'), - /** - * @description Leaves a conversation. - * @see {@link https://api.slack.com/methods/conversations.leave `conversations.leave` API reference}. - */ - leave: bindApiCall(this, 'conversations.leave'), - /** - * @description List all channels in a Slack team. - * @see {@link https://api.slack.com/methods/conversations.list `conversations.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'conversations.list'), - /** - * @description Lists shared channel invites that have been generated or received but have not been approved by - * all parties. - * @see {@link https://api.slack.com/methods/conversations.listConnectInvites `conversations.listConnectInvites` API reference}. - */ - listConnectInvites: bindApiCallWithOptionalArgument(this, 'conversations.listConnectInvites'), - /** - * @description Sets the read cursor in a channel. - * @see {@link https://api.slack.com/methods/conversations.mark `conversations.mark` API reference}. - */ - mark: bindApiCall(this, 'conversations.mark'), - /** - * @description Retrieve members of a conversation. - * @see {@link https://api.slack.com/methods/conversations.members `conversations.members` API reference}. - */ - members: bindApiCall(this, 'conversations.members'), - /** - * @description Opens or resumes a direct message or multi-person direct message. - * @see {@link https://api.slack.com/methods/conversations.open `conversations.open` API reference}. - */ - open: bindApiCall(this, 'conversations.open'), - /** - * @description Renames a conversation. - * @see {@link https://api.slack.com/methods/conversations.rename `conversations.rename` API reference}. - */ - rename: bindApiCall(this, 'conversations.rename'), - /** - * @description Retrieve a thread of messages posted to a conversation. - * @see {@link https://api.slack.com/methods/conversations.replies `conversations.replies` API reference}. - */ - replies: bindApiCall(this, 'conversations.replies'), - requestSharedInvite: { - /** - * @description Approves a request to add an external user to a channel and sends them a Slack Connect invite. - * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.approve `conversations.requestSharedInvite.approve` API reference}. - */ - approve: bindApiCall(this, 'conversations.requestSharedInvite.approve'), - /** - * @description Denies a request to invite an external user to a channel. - * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.deny `conversations.requestSharedInvite.deny` API reference}. - */ - deny: bindApiCall(this, 'conversations.requestSharedInvite.deny'), - }, - /** - * @description Sets the purpose for a conversation. - * @see {@link https://api.slack.com/methods/conversations.setPurpose `conversations.setPurpose` API reference}. - */ - setPurpose: bindApiCall(this, 'conversations.setPurpose'), - /** - * @description Sets the topic for a conversation. - * @see {@link https://api.slack.com/methods/conversations.setTopic `conversations.setTopic` API reference}. - */ - setTopic: bindApiCall(this, 'conversations.setTopic'), - /** - * @description Reverses conversation archival. - * @see {@link https://api.slack.com/methods/conversations.unarchive `conversations.unarchive` API reference}. - */ - unarchive: bindApiCall(this, 'conversations.unarchive'), - }; - this.dialog = { - /** - * @description Open a dialog with a user. - * @see {@link https://api.slack.com/methods/dialog.open `dialog.open` API reference}. - */ - open: bindApiCall(this, 'dialog.open'), - }; - this.dnd = { - /** - * @description Ends the current user's Do Not Disturb session immediately. - * @see {@link https://api.slack.com/methods/dnd.endDnd `dnd.endDnd` API reference}. - */ - endDnd: bindApiCallWithOptionalArgument(this, 'dnd.endDnd'), - /** - * @description Ends the current user's snooze mode immediately. - * @see {@link https://api.slack.com/methods/dnd.endSnooze `dnd.endSnooze` API reference}. - */ - endSnooze: bindApiCallWithOptionalArgument(this, 'dnd.endSnooze'), - /** - * @description Retrieves a user's current Do Not Disturb status. - * @see {@link https://api.slack.com/methods/dnd.info `dnd.info` API reference}. - */ - info: bindApiCallWithOptionalArgument(this, 'dnd.info'), - /** - * @description Turns on Do Not Disturb mode for the current user, or changes its duration. - * @see {@link https://api.slack.com/methods/dnd.setSnooze `dnd.setSnooze` API reference}. - */ - setSnooze: bindApiCall(this, 'dnd.setSnooze'), - /** - * @description Retrieves the Do Not Disturb status for up to 50 users on a team. - * @see {@link https://api.slack.com/methods/dnd.teamInfo `dnd.teamInfo` API reference}. - */ - teamInfo: bindApiCall(this, 'dnd.teamInfo'), - }; - this.emoji = { - /** - * @description Lists custom emoji for a team. - * @see {@link https://api.slack.com/methods/emoji.list `emoji.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'emoji.list'), - }; - this.files = { - /** - * @description Finishes an upload started with {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal`}. - * @see {@link https://api.slack.com/methods/files.completeUploadExternal `files.completeUploadExternal` API reference}. - */ - completeUploadExternal: bindApiCall(this, 'files.completeUploadExternal'), - /** - * @description Deletes a file. - * @see {@link https://api.slack.com/methods/files.delete `files.delete` API reference}. - */ - delete: bindApiCall(this, 'files.delete'), - /** - * @description Gets a URL for an edge external file upload. - * @see {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal` API reference}. - */ - getUploadURLExternal: bindApiCall(this, 'files.getUploadURLExternal'), - /** - * @description Gets information about a file. - * @see {@link https://api.slack.com/methods/files.info `files.info` API reference}. - */ - info: bindApiCall(this, 'files.info'), - /** - * @description List files for a team, in a channel, or from a user with applied filters. - * @see {@link https://api.slack.com/methods/files.list `files.list` API reference}. - */ - list: bindApiCall(this, 'files.list'), - /** - * @description Revokes public/external sharing access for a file. - * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. - */ - revokePublicURL: bindApiCall(this, 'files.revokePublicURL'), - /** - * @description Enables a file for public/external sharing. - * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. - */ - sharedPublicURL: bindApiCall(this, 'files.sharedPublicURL'), - /** - * @description Uploads or creates a file. - * @deprecated Use `uploadV2` instead. See {@link https://api.slack.com/changelog/2024-04-a-better-way-to-upload-files-is-here-to-stay our post on retiring `files.upload`}. - * @see {@link https://api.slack.com/methods/files.upload `files.upload` API reference}. - */ - upload: bindApiCall(this, 'files.upload'), - /** - * @description Custom method to support a new way of uploading files to Slack. - * Supports a single file upload - * Supply: - * - (required) single file or content - * - (optional) channel, alt_text, snippet_type, - * Supports multiple file uploads - * Supply: - * - multiple upload_files - * Will try to honor both single file or content data supplied as well - * as multiple file uploads property. - * @see {@link https://slack.dev/node-slack-sdk/web-api#upload-a-file `@slack/web-api` Upload a file documentation}. - */ - uploadV2: bindFilesUploadV2(this), - comments: { - /** - * @description Deletes an existing comment on a file. - * @see {@link https://api.slack.com/methods/files.comments.delete `files.comments.delete` API reference}. - */ - delete: bindApiCall(this, 'files.comments.delete'), - }, - remote: { - /** - * @description Adds a file from a remote service. - * @see {@link https://api.slack.com/methods/files.remote.add `files.remote.add` API reference}. - */ - add: bindApiCall(this, 'files.remote.add'), - /** - * @description Retrieve information about a remote file added to Slack. - * @see {@link https://api.slack.com/methods/files.remote.info `files.remote.info` API reference}. - */ - info: bindApiCall(this, 'files.remote.info'), - /** - * @description List remote files added to Slack. - * @see {@link https://api.slack.com/methods/files.remote.list `files.remote.list` API reference}. - */ - list: bindApiCall(this, 'files.remote.list'), - /** - * @description Remove a remote file. - * @see {@link https://api.slack.com/methods/files.remote.remove `files.remote.remove` API reference}. - */ - remove: bindApiCall(this, 'files.remote.remove'), - /** - * @description Share a remote file into a channel. - * @see {@link https://api.slack.com/methods/files.remote.share `files.remote.share` API reference}. - */ - share: bindApiCall(this, 'files.remote.share'), - /** - * @description Updates an existing remote file. - * @see {@link https://api.slack.com/methods/files.remote.update `files.remote.update` API reference}. - */ - update: bindApiCall(this, 'files.remote.update'), - }, - }; - this.functions = { - /** - * @description Signal the failure to execute a Custom Function. - * @see {@link https://api.slack.com/methods/functions.completeError `functions.completeError` API reference}. - */ - completeError: bindApiCall(this, 'functions.completeError'), - /** - * @description Signal the successful completion of a Custom Function. - * @see {@link https://api.slack.com/methods/functions.completeSuccess `functions.completeSuccess` API reference}. - */ - completeSuccess: bindApiCall(this, 'functions.completeSuccess'), - }; - this.migration = { - /** - * @description For Enterprise Grid workspaces, map local user IDs to global user IDs. - * @see {@link https://api.slack.com/methods/migration.exchange `migration.exchange` API reference}. - */ - exchange: bindApiCall(this, 'migration.exchange'), - }; - this.oauth = { - /** - * @description Exchanges a temporary OAuth verifier code for an access token. - * @deprecated This is a legacy method only used by classic Slack apps. Use `oauth.v2.access` for new Slack apps. - * @see {@link https://api.slack.com/methods/oauth.access `oauth.access` API reference}. - */ - access: bindApiCall(this, 'oauth.access'), - v2: { - /** - * @description Exchanges a temporary OAuth verifier code for an access token. - * @see {@link https://api.slack.com/methods/oauth.v2.access `oauth.v2.access` API reference}. - */ - access: bindApiCall(this, 'oauth.v2.access'), - /** - * @description Exchanges a legacy access token for a new expiring access token and refresh token. - * @see {@link https://api.slack.com/methods/oauth.v2.exchange `oauth.v2.exchange` API reference}. - */ - exchange: bindApiCall(this, 'oauth.v2.exchange'), - }, - }; - this.openid = { - connect: { - /** - * @description Exchanges a temporary OAuth verifier code for an access token for {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. - * @see {@link https://api.slack.com/methods/openid.connect.token `openid.connect.token` API reference}. - */ - token: bindApiCall(this, 'openid.connect.token'), - /** - * @description Get the identity of a user who has authorized {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. - * @see {@link https://api.slack.com/methods/openid.connect.userInfo `openid.connect.userInfo` API reference}. - */ - userInfo: bindApiCallWithOptionalArgument(this, 'openid.connect.userInfo'), - }, - }; - this.pins = { - /** - * @description Pins an item to a channel. - * @see {@link https://api.slack.com/methods/pins.add `pins.add` API reference}. - */ - add: bindApiCall(this, 'pins.add'), - /** - * @description Lists items pinned to a channel. - * @see {@link https://api.slack.com/methods/pins.list `pins.list` API reference}. - */ - list: bindApiCall(this, 'pins.list'), - /** - * @description Un-pins an item from a channel. - * @see {@link https://api.slack.com/methods/pins.remove `pins.remove` API reference}. - */ - remove: bindApiCall(this, 'pins.remove'), - }; - this.reactions = { - /** - * @description Adds a reaction to an item. - * @see {@link https://api.slack.com/methods/reactions.add `reactions.add` API reference}. - */ - add: bindApiCall(this, 'reactions.add'), - /** - * @description Gets reactions for an item. - * @see {@link https://api.slack.com/methods/reactions.get `reactions.get` API reference}. - */ - get: bindApiCall(this, 'reactions.get'), - /** - * @description List reactions made by a user. - * @see {@link https://api.slack.com/methods/reactions.list `reactions.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'reactions.list'), - /** - * @description Removes a reaction from an item. - * @see {@link https://api.slack.com/methods/reactions.remove `reactions.remove` API reference}. - */ - remove: bindApiCall(this, 'reactions.remove'), - }; - // TODO: keep tabs on reminders APIs, may be deprecated once Later list APIs land - // See: https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders - this.reminders = { - /** - * @description Creates a reminder. - * @see {@link https://api.slack.com/methods/reminders.add `reminders.add` API reference}. - */ - add: bindApiCall(this, 'reminders.add'), - /** - * @description Marks a reminder as complete. - * @see {@link https://api.slack.com/methods/reminders.complete `reminders.complete` API reference}. - */ - complete: bindApiCall(this, 'reminders.complete'), - /** - * @description Deletes a reminder. - * @see {@link https://api.slack.com/methods/reminders.delete `reminders.delete` API reference}. - */ - delete: bindApiCall(this, 'reminders.delete'), - /** - * @description Gets information about a reminder. - * @see {@link https://api.slack.com/methods/reminders.info `reminders.info` API reference}. - */ - info: bindApiCall(this, 'reminders.info'), - /** - * @description Lists all reminders created by or for a given user. - * @see {@link https://api.slack.com/methods/reminders.list `reminders.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'reminders.list'), - }; - this.rtm = { - /** - * @description Starts a Real Time Messaging session. - * @see {@link https://api.slack.com/methods/rtm.connect `rtm.connect` API reference}. - */ - connect: bindApiCallWithOptionalArgument(this, 'rtm.connect'), - /** - * @description Starts a Real Time Messaging session. - * @deprecated Use `rtm.connect` instead. See {@link https://api.slack.com/changelog/2021-10-rtm-start-to-stop our post on retiring `rtm.start`}. - * @see {@link https://api.slack.com/methods/rtm.start `rtm.start` API reference}. - */ - start: bindApiCallWithOptionalArgument(this, 'rtm.start'), - }; - this.search = { - /** - * @description Searches for messages and files matching a query. - * @see {@link https://api.slack.com/methods/search.all search.all` API reference}. - */ - all: bindApiCall(this, 'search.all'), - /** - * @description Searches for files matching a query. - * @see {@link https://api.slack.com/methods/search.files search.files` API reference}. - */ - files: bindApiCall(this, 'search.files'), - /** - * @description Searches for messages matching a query. - * @see {@link https://api.slack.com/methods/search.messages search.messages` API reference}. - */ - messages: bindApiCall(this, 'search.messages'), - }; - this.team = { - /** - * @description Gets the access logs for the current team. - * @see {@link https://api.slack.com/methods/team.accessLogs `team.accessLogs` API reference}. - */ - accessLogs: bindApiCallWithOptionalArgument(this, 'team.accessLogs'), - /** - * @description Gets billable users information for the current team. - * @see {@link https://api.slack.com/methods/team.billableInfo `team.billableInfo` API reference}. - */ - billableInfo: bindApiCallWithOptionalArgument(this, 'team.billableInfo'), - billing: { - /** - * @description Reads a workspace's billing plan information. - * @see {@link https://api.slack.com/methods/team.billing.info `team.billing.info` API reference}. - */ - info: bindApiCall(this, 'team.billing.info'), - }, - externalTeams: { - /** - * @description Disconnect an external organization. - * @see {@link https://api.slack.com/methods/team.externalTeams.disconnect `team.externalTeams.disconnect` API reference}. - */ - disconnect: bindApiCall(this, 'team.externalTeams.disconnect'), - /** - * @description Returns a list of all the external teams connected and details about the connection. - * @see {@link https://api.slack.com/methods/team.externalTeams.list `team.externalTeams.list` API reference}. - */ - list: bindApiCall(this, 'team.externalTeams.list'), - }, - /** - * @description Gets information about the current team. - * @see {@link https://api.slack.com/methods/team.info `team.info` API reference}. - */ - info: bindApiCallWithOptionalArgument(this, 'team.info'), - /** - * @description Gets the integration logs for the current team. - * @see {@link https://api.slack.com/methods/team.integrationLogs `team.integrationLogs` API reference}. - */ - integrationLogs: bindApiCallWithOptionalArgument(this, 'team.integrationLogs'), - preferences: { - /** - * @description Retrieve a list of a workspace's team preferences. - * @see {@link https://api.slack.com/methods/team.preferences.list `team.preferences.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'team.preferences.list'), - }, - profile: { - /** - * @description Retrieve a team's profile. - * @see {@link https://api.slack.com/methods/team.profile.get `team.profile.get` API reference}. - */ - get: bindApiCallWithOptionalArgument(this, 'team.profile.get'), - }, - }; - this.tooling = { - tokens: { - /** - * @description Exchanges a refresh token for a new app configuration token. - * @see {@link https://api.slack.com/methods/tooling.tokens.rotate `tooling.tokens.rotate` API reference}. - */ - rotate: bindApiCall(this, 'tooling.tokens.rotate'), - }, - }; - this.usergroups = { - /** - * @description Create a User Group. - * @see {@link https://api.slack.com/methods/usergroups.create `usergroups.create` API reference}. - */ - create: bindApiCall(this, 'usergroups.create'), - /** - * @description Disable an existing User Group. - * @see {@link https://api.slack.com/methods/usergroups.disable `usergroups.disable` API reference}. - */ - disable: bindApiCall(this, 'usergroups.disable'), - /** - * @description Enable an existing User Group. - * @see {@link https://api.slack.com/methods/usergroups.enable `usergroups.enable` API reference}. - */ - enable: bindApiCall(this, 'usergroups.enable'), - /** - * @description List all User Groups for a team. - * @see {@link https://api.slack.com/methods/usergroups.list `usergroups.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, 'usergroups.list'), - /** - * @description Update an existing User Group. - * @see {@link https://api.slack.com/methods/usergroups.update `usergroups.update` API reference}. - */ - update: bindApiCall(this, 'usergroups.update'), - users: { - /** - * @description List all users in a User Group. - * @see {@link https://api.slack.com/methods/usergroups.users.list `usergroups.users.list` API reference}. - */ - list: bindApiCall(this, 'usergroups.users.list'), - /** - * @description Update the list of users in a User Group. - * @see {@link https://api.slack.com/methods/usergroups.users.update `usergroups.users.update` API reference}. - */ - update: bindApiCall(this, 'usergroups.users.update'), - }, - }; - this.users = { - /** - * @description List conversations the calling user may access. - * @see {@link https://api.slack.com/methods/users.conversations `users.conversations` API reference}. - */ - conversations: bindApiCall(this, 'users.conversations'), - /** - * @description Delete the user profile photo. - * @see {@link https://api.slack.com/methods/users.deletePhoto `users.deletePhoto` API reference}. - */ - deletePhoto: bindApiCall(this, 'users.deletePhoto'), - discoverableContacts: { - /** - * @description Lookup an email address to see if someone is on Slack. - * @see {@link https://api.slack.com/methods/users.discoverableContacts.lookup `users.discoverableContacts.lookup` API reference}. - */ - lookup: bindApiCall(this, 'users.discoverableContacts.lookup'), - }, - /** - * @description Gets user presence information. - * @see {@link https://api.slack.com/methods/users.getPresence `users.getPresence` API reference}. - */ - getPresence: bindApiCall(this, 'users.getPresence'), - /** - * @description Get a user's identity. - * @see {@link https://api.slack.com/methods/users.identity `users.identity` API reference}. - */ - identity: bindApiCall(this, 'users.identity'), - /** - * @description Gets information about a user. - * @see {@link https://api.slack.com/methods/users.info `users.info` API reference}. - */ - info: bindApiCall(this, 'users.info'), - /** - * @description Lists all users in a Slack team. - * @see {@link https://api.slack.com/methods/users.list `users.list` API reference}. - */ - list: bindApiCall(this, 'users.list'), - /** - * @description Find a user with an email address. - * @see {@link https://api.slack.com/methods/users.lookupByEmail `users.lookupByEmail` API reference}. - */ - lookupByEmail: bindApiCall(this, 'users.lookupByEmail'), - /** - * @description Set the user profile photo. - * @see {@link https://api.slack.com/methods/users.setPhoto `users.setPhoto` API reference}. - */ - setPhoto: bindApiCall(this, 'users.setPhoto'), - /** - * @description Manually sets user presence. - * @see {@link https://api.slack.com/methods/users.setPresence `users.setPresence` API reference}. - */ - setPresence: bindApiCall(this, 'users.setPresence'), - profile: { - /** - * @description Retrieve a user's profile information, including their custom status. - * @see {@link https://api.slack.com/methods/users.profile.get `users.profile.get` API reference}. - */ - get: bindApiCall(this, 'users.profile.get'), - /** - * @description Set a user's profile information, including custom status. - * @see {@link https://api.slack.com/methods/users.profile.set `users.profile.set` API reference}. - */ - set: bindApiCall(this, 'users.profile.set'), - }, - }; - this.views = { - /** - * @description Open a view for a user. - * @see {@link https://api.slack.com/methods/views.open `views.open` API reference}. - */ - open: bindApiCall(this, 'views.open'), - /** - * @description Publish a static view for a user. - * @see {@link https://api.slack.com/methods/views.publish `views.publish` API reference}. - */ - publish: bindApiCall(this, 'views.publish'), - /** - * @description Push a view onto the stack of a root view. - * @see {@link https://api.slack.com/methods/views.push `views.push` API reference}. - */ - push: bindApiCall(this, 'views.push'), - /** - * @description Update an existing view. - * @see {@link https://api.slack.com/methods/views.update `views.update` API reference}. - */ - update: bindApiCall(this, 'views.update'), - }; - // ------------------ - // Deprecated methods - // ------------------ - // TODO: breaking changes for future majors: - // - stars.* methods are marked as deprecated; once Later has APIs, these will see an official sunsetting timeline - // - workflows.* methods, Sep 12 2024: https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back - this.stars = { - /** - * @description Save an item for later. Formerly known as adding a star. - * @deprecated Stars can still be added but they can no longer be viewed or interacted with by end-users. - * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. - * @see {@link https://api.slack.com/methods/stars.add `stars.add` API reference}. - */ - add: bindApiCall(this, 'stars.add'), - /** - * @description List a user's saved items, formerly known as stars. - * @deprecated Stars can still be listed but they can no longer be viewed or interacted with by end-users. - * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. - * @see {@link https://api.slack.com/methods/stars.list `stars.list` API reference}. - */ - list: bindApiCall(this, 'stars.list'), - /** - * @description Remove a saved item from a user's saved items, formerly known as stars. - * @deprecated Stars can still be removed but they can no longer be viewed or interacted with by end-users. - * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. - * @see {@link https://api.slack.com/methods/stars.remove `stars.remove` API reference}. - */ - remove: bindApiCall(this, 'stars.remove'), - }; - this.workflows = { - /** - * @description Indicate that an app's step in a workflow completed execution. - * @deprecated Steps from Apps is deprecated. - * We're retiring all Slack app functionality around Steps from Apps in September 2024. - * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. - * @see {@link https://api.slack.com/methods/workflows.stepCompleted `workflows.stepCompleted` API reference}. - */ - stepCompleted: bindApiCall(this, 'workflows.stepCompleted'), - /** - * @description Indicate that an app's step in a workflow failed to execute. - * @deprecated Steps from Apps is deprecated. - * We're retiring all Slack app functionality around Steps from Apps in September 2024. - * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. - * @see {@link https://api.slack.com/methods/workflows.stepFailed `workflows.stepFailed` API reference}. - */ - stepFailed: bindApiCall(this, 'workflows.stepFailed'), - /** - * @description Update the configuration for a workflow step. - * @deprecated Steps from Apps is deprecated. - * We're retiring all Slack app functionality around Steps from Apps in September 2024. - * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. - * @see {@link https://api.slack.com/methods/workflows.updateStep `workflows.updateStep` API reference}. - */ - updateStep: bindApiCall(this, 'workflows.updateStep'), - }; - // Check that the class being created extends from `WebClient` rather than this class - if (new.target !== WebClient_1.WebClient && !(new.target.prototype instanceof WebClient_1.WebClient)) { - throw new Error('Attempt to inherit from WebClient methods without inheriting from WebClient'); - } - } -} -exports.Methods = Methods; -__exportStar(__nccwpck_require__(4775), exports); -//# sourceMappingURL=methods.js.map - -/***/ }), - -/***/ 1766: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.rapidRetryPolicy = exports.fiveRetriesInFiveMinutes = exports.tenRetriesInAboutThirtyMinutes = void 0; -/** - * The default retry policy. Retry up to 10 times, over the span of about 30 minutes. It's not exact because - * randomization has been added to prevent a stampeding herd problem (if all instances in your application are retrying - * a request at the exact same intervals, they are more likely to cause failures for each other). - */ -exports.tenRetriesInAboutThirtyMinutes = { - retries: 10, - factor: 1.96821, - randomize: true, -}; -/** - * Short & sweet, five retries in five minutes and then bail. - */ -exports.fiveRetriesInFiveMinutes = { - retries: 5, - factor: 3.86, -}; -/** - * This policy is just to keep the tests running fast. - */ -exports.rapidRetryPolicy = { - minTimeout: 0, - maxTimeout: 1, -}; -const policies = { - tenRetriesInAboutThirtyMinutes: exports.tenRetriesInAboutThirtyMinutes, - fiveRetriesInFiveMinutes: exports.fiveRetriesInFiveMinutes, - rapidRetryPolicy: exports.rapidRetryPolicy, -}; -exports["default"] = policies; -//# sourceMappingURL=retry-policies.js.map - -/***/ }), - -/***/ 381: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 5591: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 1324: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = -{ - parallel : __nccwpck_require__(3857), - serial : __nccwpck_require__(1054), - serialOrdered : __nccwpck_require__(3961) -}; - - -/***/ }), - -/***/ 4818: -/***/ ((module) => { - -// API -module.exports = abort; - -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); - - // reset leftover jobs - state.jobs = {}; -} - -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } -} - - -/***/ }), - -/***/ 8452: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var defer = __nccwpck_require__(9200); - -// API -module.exports = async; - -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; - - // check if async happened - defer(function() { isAsync = true; }); - - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; -} - - -/***/ }), - -/***/ 9200: -/***/ ((module) => { - -module.exports = defer; - -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); - - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } -} - - -/***/ }), - -/***/ 4902: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var async = __nccwpck_require__(8452) - , abort = __nccwpck_require__(4818) - ; - -// API -module.exports = iterate; - -/** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed - */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } - - // clean up jobs - delete state.jobs[key]; - - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; - } - - // return salvaged results - callback(error, state.results); - }); -} - -/** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else - */ -function runJob(iterator, key, item, callback) -{ - var aborter; - - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); - } - - return aborter; -} - - -/***/ }), - -/***/ 1721: -/***/ ((module) => { - -// API -module.exports = state; - -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length - } - ; - - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); - }); - } - - return initState; -} - - -/***/ }), - -/***/ 3351: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var abort = __nccwpck_require__(4818) - , async = __nccwpck_require__(8452) - ; - -// API -module.exports = terminator; - -/** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination - */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; - } - - // fast forward iteration index - this.index = this.size; - - // abort jobs - abort(this); - - // send back results we have so far - async(callback)(null, this.results); -} - - -/***/ }), - -/***/ 3857: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(4902) - , initState = __nccwpck_require__(1721) - , terminator = __nccwpck_require__(3351) - ; - -// Public API -module.exports = parallel; - -/** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function parallel(list, iterator, callback) -{ - var state = initState(list); - - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } - - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); - - state.index++; - } - - return terminator.bind(state, callback); -} - - -/***/ }), - -/***/ 1054: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(3961); - -// Public API -module.exports = serial; - -/** - * Runs iterator over provided array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); -} - - -/***/ }), - -/***/ 3961: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(4902) - , initState = __nccwpck_require__(1721) - , terminator = __nccwpck_require__(3351) - ; - -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; - -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); - - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; - } - - state.index++; - - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; - } - - // done here - callback(null, state.results); - }); - - return terminator.bind(state, callback); -} - -/* - * -- Sort methods - */ - -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; -} - -/** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function descending(a, b) -{ - return -1 * ascending(a, b); -} - - -/***/ }), - -/***/ 9380: -/***/ ((module) => { - -"use strict"; - -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; - } - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; - } - - if (begs.length) { - result = [ left, right ]; - } - } - - return result; -} - - -/***/ }), - -/***/ 4691: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var concatMap = __nccwpck_require__(7087); -var balanced = __nccwpck_require__(9380); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function platformErrorFromResult(result) { + const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError); + error.data = result; + return error; } - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; +exports.platformErrorFromResult = platformErrorFromResult; +/** + * A factory to create WebAPIRateLimitedError objects + * @param retrySec - Number of seconds that the request can be retried in + */ +function rateLimitedErrorWithDelay(retrySec) { + const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError); + error.retryAfter = retrySec; + return error; } +exports.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay; +//# sourceMappingURL=errors.js.map -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } +/***/ }), - return expand(escapeBraces(str), true).map(unescapeBraces); -} +/***/ 2577: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function identity(e) { - return e; -} +"use strict"; -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); +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()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.buildInvalidFilesUploadParamError = exports.buildMultipleChannelsErrorMsg = exports.buildChannelsWarning = exports.buildFilesUploadMissingMessage = exports.buildGeneralFilesUploadWarning = exports.buildLegacyMethodWarning = exports.buildMissingExtensionWarning = exports.buildMissingFileNameWarning = exports.buildLegacyFileTypeWarning = exports.buildFileSizeErrorMsg = exports.buildMissingFileIdError = exports.warnIfLegacyFileType = exports.warnIfMissingOrInvalidFileNameAndDefault = exports.errorIfInvalidOrMissingFileData = exports.errorIfChannelsCsv = exports.warnIfChannels = exports.warnIfNotUsingFilesUploadV2 = exports.getAllFileUploadsToComplete = exports.getFileDataAsStream = exports.getFileDataLength = exports.getFileData = exports.getMultipleFileUploadJobs = exports.getFileUploadJob = void 0; +const node_fs_1 = __nccwpck_require__(3024); +const node_stream_1 = __nccwpck_require__(7075); +const errors_1 = __nccwpck_require__(8486); +function getFileUploadJob(options, logger) { + var _a, _b, _c, _d; + return __awaiter(this, void 0, void 0, function* () { + // Validate parameters + warnIfLegacyFileType(options, logger); + warnIfChannels(options, logger); + errorIfChannelsCsv(options); + const fileName = warnIfMissingOrInvalidFileNameAndDefault(options, logger); + const fileData = yield getFileData(options); + const fileDataBytesLength = getFileDataLength(fileData); + const fileUploadJob = { + // supplied by user + alt_text: options.alt_text, + channel_id: (_a = options.channels) !== null && _a !== void 0 ? _a : options.channel_id, + filename: (_b = options.filename) !== null && _b !== void 0 ? _b : fileName, + initial_comment: options.initial_comment, + snippet_type: options.snippet_type, + title: (_d = (_c = options.title) !== null && _c !== void 0 ? _c : options.filename) !== null && _d !== void 0 ? _d : fileName, // default title to filename unless otherwise specified + // calculated + data: fileData, + length: fileDataBytesLength, + }; + if ('thread_ts' in options) { + fileUploadJob.thread_ts = options.thread_ts; + } + if ('token' in options) { + fileUploadJob.token = options.token; + } + if ('content' in options) { + return Object.assign({ content: options.content }, fileUploadJob); + } + if ('file' in options) { + return Object.assign({ file: options.file }, fileUploadJob); + } + throw (0, errors_1.errorWithCode)(new Error('Either a file or content field is required for valid file upload. You must supply one'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + }); } - -function lte(i, y) { - return i <= y; +exports.getFileUploadJob = getFileUploadJob; +/** + * Returns an array of files upload entries when `file_uploads` is supplied. + * **Note** + * file_uploads should be set when multiple files are intended to be attached to a + * single message. To support this, we handle options supplied with + * top level `initial_comment`, `thread_ts`, `channel_id` and `file_uploads` parameters. + * ```javascript + * const res = await client.files.uploadV2({ + * initial_comment: 'Here are the files!', + * thread_ts: '1223313423434.131321', + * channel_id: 'C12345', + * file_uploads: [ + * { + * file: './test/fixtures/test-txt.txt', + * filename: 'test-txt.txt', + * }, + * { + * file: './test/fixtures/test-png.png', + * filename: 'test-png.png', + * }, + * ], + * }); + * ``` + * @param options provided by user + */ +function getMultipleFileUploadJobs(options, logger) { + return __awaiter(this, void 0, void 0, function* () { + if ('file_uploads' in options) { + // go through each file_upload and create a job for it + return Promise.all(options.file_uploads.map((upload) => { + // ensure no omitted properties included in files_upload entry + // these properties are valid only at the top-level, not + // inside file_uploads. + const { channel_id, channels, initial_comment, thread_ts } = upload; + if (channel_id || channels || initial_comment || thread_ts) { + throw (0, errors_1.errorWithCode)(new Error(buildInvalidFilesUploadParamError()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + // takes any channel_id, initial_comment and thread_ts + // supplied at the top level. + const uploadJobArgs = Object.assign(Object.assign({}, upload), { channels: options.channels, channel_id: options.channel_id, initial_comment: options.initial_comment }); + if ('thread_ts' in options) { + uploadJobArgs.thread_ts = options.thread_ts; + } + if ('token' in options) { + uploadJobArgs.token = options.token; + } + if ('content' in upload) { + return getFileUploadJob(Object.assign({ content: upload.content }, uploadJobArgs), logger); + } + if ('file' in upload) { + return getFileUploadJob(Object.assign({ file: upload.file }, uploadJobArgs), logger); + } + throw (0, errors_1.errorWithCode)(new Error('Either a file or content field is required for valid file upload. You must supply one'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + })); + } + throw new Error(buildFilesUploadMissingMessage()); + }); } -function gte(i, y) { - return i >= y; +exports.getMultipleFileUploadJobs = getMultipleFileUploadJobs; +// Helpers to build the FileUploadJob +/** + * Returns a single file upload's data + * @param options + * @returns Binary data representation of file + */ +function getFileData(options) { + return __awaiter(this, void 0, void 0, function* () { + errorIfInvalidOrMissingFileData(options); + if ('file' in options) { + const { file } = options; + // try to handle as buffer + if (Buffer.isBuffer(file)) + return file; + // try to handle as filepath + if (typeof file === 'string') { + // try to read file as if the string was a file path + try { + const dataBuffer = (0, node_fs_1.readFileSync)(file); + return dataBuffer; + } + catch (error) { + throw (0, errors_1.errorWithCode)(new Error(`Unable to resolve file data for ${file}. Please supply a filepath string, or binary data Buffer or String directly.`), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + } + // try to handle as Readable + const data = yield getFileDataAsStream(file); + if (data) + return data; + } + if ('content' in options) + return Buffer.from(options.content); + // general catch-all error + throw (0, errors_1.errorWithCode)(new Error('There was an issue getting the file data for the file or content supplied'), errors_1.ErrorCode.FileUploadReadFileDataError); + }); } - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); +exports.getFileData = getFileData; +function getFileDataLength(data) { + if (data) { + return Buffer.byteLength(data, 'utf8'); } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; + throw (0, errors_1.errorWithCode)(new Error(buildFileSizeErrorMsg()), errors_1.ErrorCode.FileUploadReadFileDataError); +} +exports.getFileDataLength = getFileDataLength; +function getFileDataAsStream(readable) { + return __awaiter(this, void 0, void 0, function* () { + const chunks = []; + return new Promise((resolve, reject) => { + readable.on('readable', () => { + let chunk; + // biome-ignore lint/suspicious/noAssignInExpressions: being terse, this is OK + while ((chunk = readable.read()) !== null) { + chunks.push(chunk); + } + }); + readable.on('end', () => { + if (chunks.length > 0) { + const content = Buffer.concat(chunks); + resolve(content); + } + else { + reject(Error('No data in supplied file')); + } + }); }); - } - } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } + }); +} +exports.getFileDataAsStream = getFileDataAsStream; +/** + * Filters through all fileUploads and groups them into jobs for completion + * based on combination of channel_id, thread_ts, initial_comment. + * {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} allows for multiple + * files to be uploaded with a message (`initial_comment`), and as a threaded message (`thread_ts`) + * In order to be grouped together, file uploads must have like properties. + * @param fileUploads + * @returns + */ +function getAllFileUploadsToComplete(fileUploads) { + const toComplete = {}; + for (const upload of fileUploads) { + const { channel_id, thread_ts, initial_comment, file_id, title } = upload; + if (file_id) { + const compareString = `:::${channel_id}:::${thread_ts}:::${initial_comment}`; + if (!Object.prototype.hasOwnProperty.call(toComplete, compareString)) { + toComplete[compareString] = { + files: [{ id: file_id, title }], + channel_id, + initial_comment, + }; + if (thread_ts) { + toComplete[compareString].thread_ts = upload.thread_ts; + } + if ('token' in upload) { + toComplete[compareString].token = upload.token; + } + } + else { + toComplete[compareString].files.push({ + id: file_id, + title, + }); + } + } + else { + throw new Error(buildMissingFileIdError()); } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); } - } - - return expansions; + return toComplete; } - - - -/***/ }), - -/***/ 5630: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(9023); -var Stream = (__nccwpck_require__(2203).Stream); -var DelayedStream = __nccwpck_require__(2710); - -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; +exports.getAllFileUploadsToComplete = getAllFileUploadsToComplete; +// Validation +/** + * Advise to use the files.uploadV2 method over legacy files.upload method and over + * lower-level utilities. + * @param method + * @param logger + */ +function warnIfNotUsingFilesUploadV2(method, logger) { + const targetMethods = ['files.upload']; + const isTargetMethod = targetMethods.includes(method); + if (method === 'files.upload') + logger.warn(buildLegacyMethodWarning(method)); + if (isTargetMethod) + logger.info(buildGeneralFilesUploadWarning()); +} +exports.warnIfNotUsingFilesUploadV2 = warnIfNotUsingFilesUploadV2; +/** + * `channels` param is supported but only when a single channel is specified. + * @param options + * @param logger + */ +function warnIfChannels(options, logger) { + if (options.channels) + logger.warn(buildChannelsWarning()); +} +exports.warnIfChannels = warnIfChannels; +/** + * v1 files.upload supported `channels` parameter provided as a comma-separated + * string of values, e.g. 'C1234,C5678'. V2 no longer supports this csv value. + * You may still supply `channels` with a single channel string value e.g. 'C1234' + * but it is highly encouraged to supply `channel_id` instead. + * @param options + */ +function errorIfChannelsCsv(options) { + const channels = options.channels ? options.channels.split(',') : []; + if (channels.length > 1) { + throw (0, errors_1.errorWithCode)(new Error(buildMultipleChannelsErrorMsg()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } } -util.inherits(CombinedStream, Stream); - -CombinedStream.create = function(options) { - var combinedStream = new this(); - - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } - - return combinedStream; -}; - -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); -}; - -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams, - }); - stream.on('data', this._checkDataSize.bind(this)); - stream = newStream; +exports.errorIfChannelsCsv = errorIfChannelsCsv; +/** + * Checks for either a file or content property and errors if missing + * @param options + */ +function errorIfInvalidOrMissingFileData(options) { + const hasFile = 'file' in options; + const hasContent = 'content' in options; + if (!(hasFile || hasContent) || (hasFile && hasContent)) { + throw (0, errors_1.errorWithCode)(new Error('Either a file or content field is required for valid file upload. You cannot supply both'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); } - - this._handleErrors(stream); - - if (this.pauseStreams) { - stream.pause(); + if ('file' in options) { + const { file } = options; + if (file && !(typeof file === 'string' || Buffer.isBuffer(file) || file instanceof node_stream_1.Readable)) { + throw (0, errors_1.errorWithCode)(new Error('file must be a valid string path, buffer or Readable'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } } - } - - this._streams.push(stream); - return this; -}; - -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; -}; - -CombinedStream.prototype._getNext = function() { - this._currentStream = null; - - if (this._insideLoop) { - this._pendingNext = true; - return; // defer call - } - - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } -}; - -CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); - - - if (typeof stream == 'undefined') { - this.end(); - return; - } - - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } - - var getStream = stream; - getStream(function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('data', this._checkDataSize.bind(this)); - this._handleErrors(stream); + if ('content' in options && options.content && typeof options.content !== 'string') { + throw (0, errors_1.errorWithCode)(new Error('content must be a string'), errors_1.ErrorCode.FileUploadInvalidArgumentsError); } - - this._pipeNext(stream); - }.bind(this)); -}; - -CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; - - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('end', this._getNext.bind(this)); - stream.pipe(this, {end: false}); - return; - } - - var value = stream; - this.write(value); - this._getNext(); -}; - -CombinedStream.prototype._handleErrors = function(stream) { - var self = this; - stream.on('error', function(err) { - self._emitError(err); - }); -}; - -CombinedStream.prototype.write = function(data) { - this.emit('data', data); -}; - -CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } - - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); - this.emit('pause'); -}; - -CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } - - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); - this.emit('resume'); -}; - -CombinedStream.prototype.end = function() { - this._reset(); - this.emit('end'); -}; - -CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit('close'); -}; - -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; -}; - -CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } - - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; - this._emitError(new Error(message)); -}; - -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; - - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; +} +exports.errorIfInvalidOrMissingFileData = errorIfInvalidOrMissingFileData; +/** + * @param options + * @param logger + * @returns filename if it exists + */ +function warnIfMissingOrInvalidFileNameAndDefault(options, logger) { + var _a; + const DEFAULT_FILETYPE = 'txt'; + const DEFAULT_FILENAME = `file.${(_a = options.filetype) !== null && _a !== void 0 ? _a : DEFAULT_FILETYPE}`; + const { filename } = options; + if (!filename) { + // Filename was an optional property in legacy method + logger.warn(buildMissingFileNameWarning()); + return DEFAULT_FILENAME; + } + if (filename.split('.').length < 2) { + // likely filename is missing extension + logger.warn(buildMissingExtensionWarning(filename)); + } + return filename; +} +exports.warnIfMissingOrInvalidFileNameAndDefault = warnIfMissingOrInvalidFileNameAndDefault; +/** + * `filetype` param is no longer supported and will be ignored + * @param options + * @param logger + */ +function warnIfLegacyFileType(options, logger) { + if (options.filetype) { + logger.warn(buildLegacyFileTypeWarning()); } +} +exports.warnIfLegacyFileType = warnIfLegacyFileType; +// Validation message utilities +function buildMissingFileIdError() { + return 'Missing required file id for file upload completion'; +} +exports.buildMissingFileIdError = buildMissingFileIdError; +function buildFileSizeErrorMsg() { + return 'There was an issue calculating the size of your file'; +} +exports.buildFileSizeErrorMsg = buildFileSizeErrorMsg; +function buildLegacyFileTypeWarning() { + return ('filetype is no longer a supported field in files.uploadV2.' + + ' \nPlease remove this field. To indicate file type, please do so via the required filename property' + + ' using the appropriate file extension, e.g. image.png, text.txt'); +} +exports.buildLegacyFileTypeWarning = buildLegacyFileTypeWarning; +function buildMissingFileNameWarning() { + return ('filename is a required field for files.uploadV2. \n For backwards compatibility and ease of migration, ' + + 'defaulting the filename. For best experience and consistent unfurl behavior, you' + + ' should set the filename property with correct file extension, e.g. image.png, text.txt'); +} +exports.buildMissingFileNameWarning = buildMissingFileNameWarning; +function buildMissingExtensionWarning(filename) { + return `filename supplied '${filename}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`; +} +exports.buildMissingExtensionWarning = buildMissingExtensionWarning; +function buildLegacyMethodWarning(method) { + return `${method} may cause some issues like timeouts for relatively large files.`; +} +exports.buildLegacyMethodWarning = buildLegacyMethodWarning; +function buildGeneralFilesUploadWarning() { + return ('Our latest recommendation is to use client.files.uploadV2() method, ' + + 'which is mostly compatible and much stabler, instead.'); +} +exports.buildGeneralFilesUploadWarning = buildGeneralFilesUploadWarning; +function buildFilesUploadMissingMessage() { + return 'Something went wrong with processing file_uploads'; +} +exports.buildFilesUploadMissingMessage = buildFilesUploadMissingMessage; +function buildChannelsWarning() { + return ("Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, " + + "we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."); +} +exports.buildChannelsWarning = buildChannelsWarning; +function buildMultipleChannelsErrorMsg() { + return 'Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead.'; +} +exports.buildMultipleChannelsErrorMsg = buildMultipleChannelsErrorMsg; +function buildInvalidFilesUploadParamError() { + return ('You may supply file_uploads only for a single channel, comment, thread respectively. ' + + 'Therefore, please supply any channel_id, initial_comment, thread_ts in the top-layer.'); +} +exports.buildInvalidFilesUploadParamError = buildInvalidFilesUploadParamError; +//# sourceMappingURL=file-upload.js.map - self.dataSize += stream.dataSize; - }); +/***/ }), - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } -}; +/***/ 4060: +/***/ ((__unused_webpack_module, exports) => { -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Build a Promise that will resolve after the specified number of milliseconds. + * @param ms milliseconds to wait + * @param value value for eventual resolution + */ +function delay(ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} +exports["default"] = delay; +//# sourceMappingURL=helpers.js.map /***/ }), -/***/ 7087: -/***/ ((module) => { +/***/ 5105: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - return res; + Object.defineProperty(o, k2, desc); +}) : (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); }; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.addAppMetadata = exports.retryPolicies = exports.ErrorCode = exports.LogLevel = exports.WebClientEvent = exports.WebClient = void 0; +var WebClient_1 = __nccwpck_require__(4048); +Object.defineProperty(exports, "WebClient", ({ enumerable: true, get: function () { return WebClient_1.WebClient; } })); +Object.defineProperty(exports, "WebClientEvent", ({ enumerable: true, get: function () { return WebClient_1.WebClientEvent; } })); +var logger_1 = __nccwpck_require__(4385); +Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return logger_1.LogLevel; } })); +var errors_1 = __nccwpck_require__(8486); +Object.defineProperty(exports, "ErrorCode", ({ enumerable: true, get: function () { return errors_1.ErrorCode; } })); +var retry_policies_1 = __nccwpck_require__(1766); +Object.defineProperty(exports, "retryPolicies", ({ enumerable: true, get: function () { return __importDefault(retry_policies_1).default; } })); +var instrument_1 = __nccwpck_require__(9224); +Object.defineProperty(exports, "addAppMetadata", ({ enumerable: true, get: function () { return instrument_1.addAppMetadata; } })); +__exportStar(__nccwpck_require__(9339), exports); +__exportStar(__nccwpck_require__(381), exports); +__exportStar(__nccwpck_require__(5591), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 6110: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; +/***/ 9224: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getUserAgent = exports.addAppMetadata = void 0; +const os = __importStar(__nccwpck_require__(8161)); +const node_path_1 = __nccwpck_require__(6760); +const packageJson = __nccwpck_require__(6734); /** - * Colors. + * Replaces occurrences of '/' with ':' in a string, since '/' is meaningful inside User-Agent strings as a separator. */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - +function replaceSlashes(s) { + return s.replace('/', ':'); +} +// TODO: for the deno build (see the `npm run build:deno` npm run script), we could replace the `os-browserify` npm +// module shim with our own shim leveraging the deno beta compatibility layer for node's `os` module (for more info +// see https://deno.land/std@0.116.0/node/os.ts). At the time of writing this TODO (2021/11/25), this required deno +// v1.16.2 and use of the --unstable flag. Once support for this exists without the --unstable flag, we can improve +// the `os` module deno shim to correctly report operating system from a deno runtime. Until then, the below `os`- +// based code will report "browser/undefined" from a deno runtime. +const baseUserAgent = `${replaceSlashes(packageJson.name)}/${packageJson.version} ` + + `${(0, node_path_1.basename)(process.title)}/${process.version.replace('v', '')} ` + + `${os.platform()}/${os.release()}`; +const appMetadata = {}; /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * Appends the app metadata into the User-Agent value + * @param appMetadata.name - name of tool to be counted in instrumentation + * @param appMetadata.version - version of tool to be counted in instrumentation */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +function addAppMetadata({ name, version }) { + appMetadata[replaceSlashes(name)] = version; } - +exports.addAppMetadata = addAppMetadata; /** - * Colorize log arguments if enabled. - * - * @api public + * Returns the current User-Agent value for instrumentation */ +function getUserAgent() { + const appIdentifier = Object.entries(appMetadata) + .map(([name, version]) => `${name}/${version}`) + .join(' '); + // only prepend the appIdentifier when its not empty + return (appIdentifier.length > 0 ? `${appIdentifier} ` : '') + baseUserAgent; +} +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=instrument.js.map -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); +/***/ }), - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +/***/ 4385: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - args.splice(lastC, 0, c); -} +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLogger = exports.LogLevel = void 0; +const logger_1 = __nccwpck_require__(9234); +var logger_2 = __nccwpck_require__(9234); +Object.defineProperty(exports, "LogLevel", ({ enumerable: true, get: function () { return logger_2.LogLevel; } })); +let instanceCount = 0; /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public + * INTERNAL interface for getting or creating a named Logger. */ -exports.log = console.debug || console.log || (() => {}); +function getLogger(name, level, existingLogger) { + // Get a unique ID for the logger. + const instanceId = instanceCount; + instanceCount += 1; + // Set up the logger. + const logger = (() => { + if (existingLogger !== undefined) { + return existingLogger; + } + return new logger_1.ConsoleLogger(); + })(); + logger.setName(`web-api:${name}:${instanceId}`); + if (level !== undefined) { + logger.setLevel(level); + } + return logger; +} +exports.getLogger = getLogger; +//# sourceMappingURL=logger.js.map +/***/ }), + +/***/ 9339: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Methods = void 0; +const eventemitter3_1 = __nccwpck_require__(2415); +const WebClient_1 = __nccwpck_require__(4048); /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Binds a certain `method` and its (required) arguments and result types to the `apiCall` method in `WebClient`. */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function bindApiCall(self, method) { + const apiMethod = self.apiCall.bind(self, method); + return apiMethod; } - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Binds a certain `method` and its (required) arguments and result types to the `apiCall` method in `WebClient`. */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; +function bindApiCallWithOptionalArgument(self, method) { + const apiMethod = self.apiCall.bind(self, method); + return apiMethod; +} +function bindFilesUploadV2(self) { + return self.filesUploadV2.bind(self); } - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * A class that defines all Web API methods, their arguments type, their response type, and binds those methods to the + * `apiCall` class method. */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +class Methods extends eventemitter3_1.EventEmitter { + constructor() { + super(); + this.admin = { + analytics: { + /** + * @description Retrieve analytics data for a given date, presented as a compressed JSON file. + * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. + */ + getFile: bindApiCall(this, 'admin.analytics.getFile'), + }, + apps: { + activities: { + /** + * @description Get logs for a specified team/org. + * @see {@link https://api.slack.com/methods/admin.apps.activities.list `admin.apps.activities.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'admin.apps.activities.list'), + }, + /** + * @description Approve an app for installation on a workspace. + * @see {@link https://api.slack.com/methods/admin.apps.approve `admin.apps.approve` API reference}. + */ + approve: bindApiCall(this, 'admin.apps.approve'), + approved: { + /** + * @description List approved apps for an org or workspace. + * @see {@link https://api.slack.com/methods/admin.apps.approved.list `admin.apps.approved.list` API reference}. + */ + list: bindApiCall(this, 'admin.apps.approved.list'), + }, + /** + * @description Clear an app resolution. + * @see {@link https://api.slack.com/methods/admin.apps.clearResolution `admin.apps.clearResolution` API reference}. + */ + clearResolution: bindApiCall(this, 'admin.apps.clearResolution'), + config: { + /** + * @description Look up the app config for connectors by their IDs. + * @see {@link https://api.slack.com/methods/admin.apps.config.lookup `admin.apps.config.lookup` API reference}. + */ + lookup: bindApiCall(this, 'admin.apps.config.lookup'), + /** + * @description Set the app config for a connector. + * @see {@link https://api.slack.com/methods/admin.apps.config.set `admin.apps.config.set` API reference}. + */ + set: bindApiCall(this, 'admin.apps.config.set'), + }, + requests: { + /** + * @description Cancel app request for team. + * @see {@link https://api.slack.com/methods/admin.apps.requests.cancel `admin.apps.requests.cancel` API reference}. + */ + cancel: bindApiCall(this, 'admin.apps.requests.cancel'), + /** + * @description List app requests for a team/workspace. + * @see {@link https://api.slack.com/methods/admin.apps.requests.list `admin.apps.requests.list` API reference}. + */ + list: bindApiCall(this, 'admin.apps.requests.list'), + }, + /** + * @description Restrict an app for installation on a workspace. + * @see {@link https://api.slack.com/methods/admin.apps.restrict `admin.apps.restrict` API reference}. + */ + restrict: bindApiCall(this, 'admin.apps.restrict'), + restricted: { + /** + * @description List restricted apps for an org or workspace. + * @see {@link https://api.slack.com/methods/admin.apps.restricted.list `admin.apps.restricted.list` API reference}. + */ + list: bindApiCall(this, 'admin.apps.restricted.list'), + }, + /** + * @description Uninstall an app from one or many workspaces, or an entire enterprise organization. + * @see {@link https://api.slack.com/methods/admin.apps.uninstall `admin.apps.uninstall` API reference}. + */ + uninstall: bindApiCall(this, 'admin.apps.uninstall'), + }, + auth: { + policy: { + /** + * @description Assign entities to a particular authentication policy. + * @see {@link https://api.slack.com/methods/admin.auth.policy.assignEntities `admin.auth.policy.assignEntities` API reference}. + */ + assignEntities: bindApiCall(this, 'admin.auth.policy.assignEntities'), + /** + * @description Fetch all the entities assigned to a particular authentication policy by name. + * @see {@link https://api.slack.com/methods/admin.auth.policy.getEntities `admin.auth.policy.getEntities` API reference}. + */ + getEntities: bindApiCall(this, 'admin.auth.policy.getEntities'), + /** + * @description Remove specified entities from a specified authentication policy. + * @see {@link https://api.slack.com/methods/admin.auth.policy.removeEntities `admin.auth.policy.removeEntities` API reference}. + */ + removeEntities: bindApiCall(this, 'admin.auth.policy.removeEntities'), + }, + }, + barriers: { + /** + * @description Create an Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.create `admin.barriers.create` API reference}. + */ + create: bindApiCall(this, 'admin.barriers.create'), + /** + * @description Delete an existing Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.delete `admin.barriers.delete` API reference}. + */ + delete: bindApiCall(this, 'admin.barriers.delete'), + /** + * @description Get all Information Barriers for your organization. + * @see {@link https://api.slack.com/methods/admin.barriers.list `admin.barriers.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'admin.barriers.list'), + /** + * @description Update an existing Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.update `admin.barriers.update` API reference}. + */ + update: bindApiCall(this, 'admin.barriers.update'), + }, + conversations: { + /** + * @description Archive a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.archive `admin.conversations.archive` API reference}. + */ + archive: bindApiCall(this, 'admin.conversations.archive'), + /** + * @description Archive public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkArchive `admin.conversations.bulkArchive` API reference}. + */ + bulkArchive: bindApiCall(this, 'admin.conversations.bulkArchive'), + /** + * @description Delete public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkDelet `admin.conversations.bulkDelete` API reference}. + */ + bulkDelete: bindApiCall(this, 'admin.conversations.bulkDelete'), + /** + * @description Move public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkMove `admin.conversations.bulkMove` API reference}. + */ + bulkMove: bindApiCall(this, 'admin.conversations.bulkMove'), + /** + * @description Convert a public channel to a private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.convertToPrivate `admin.conversations.convertToPrivate` API reference}. + */ + convertToPrivate: bindApiCall(this, 'admin.conversations.convertToPrivate'), + /** + * @description Convert a private channel to a public channel. + * @see {@link https://api.slack.com/methods/admin.conversations.convertToPublic `admin.conversations.convertToPublic` API reference}. + */ + convertToPublic: bindApiCall(this, 'admin.conversations.convertToPublic'), + /** + * @description Create a public or private channel-based conversation. + * @see {@link https://api.slack.com/methods/admin.conversations.create `admin.conversations.create` API reference}. + */ + create: bindApiCall(this, 'admin.conversations.create'), + /** + * @description Delete a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.delete `admin.conversations.delete` API reference}. + */ + delete: bindApiCall(this, 'admin.conversations.delete'), + /** + * @description Disconnect a connected channel from one or more workspaces. + * @see {@link https://api.slack.com/methods/admin.conversations.disconnectShared `admin.conversations.disconnectShared` API reference}. + */ + disconnectShared: bindApiCall(this, 'admin.conversations.disconnectShared'), + ekm: { + /** + * @description List all disconnected channels — i.e., channels that were once connected to other workspaces + * and then disconnected — and the corresponding original channel IDs for key revocation with EKM. + * @see {@link https://api.slack.com/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo `admin.conversations.ekm.listOriginalConnectedChannelInfo` API reference}. + */ + listOriginalConnectedChannelInfo: bindApiCallWithOptionalArgument(this, 'admin.conversations.ekm.listOriginalConnectedChannelInfo'), + }, + /** + * @description Get conversation preferences for a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.getConversationPrefs `admin.conversations.getConversationPrefs` API reference}. + */ + getConversationPrefs: bindApiCall(this, 'admin.conversations.getConversationPrefs'), + /** + * @description Get a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.getCustomRetention `admin.conversations.getCustomRetention` API reference}. + */ + getCustomRetention: bindApiCall(this, 'admin.conversations.getCustomRetention'), + /** + * @description Get all the workspaces a given public or private channel is connected to within + * this Enterprise org. + * @see {@link https://api.slack.com/methods/admin.conversations.getTeams `admin.conversations.getTeams` API reference}. + */ + getTeams: bindApiCall(this, 'admin.conversations.getTeams'), + /** + * @description Invite a user to a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.invite `admin.conversations.invite` API reference}. + */ + invite: bindApiCall(this, 'admin.conversations.invite'), + /** + * @description Returns channels on the given team using the filters. + * @see {@link https://api.slack.com/methods/admin.conversations.lookup `admin.conversations.lookup` API reference}. + */ + lookup: bindApiCall(this, 'admin.conversations.lookup'), + /** + * @description Remove a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.removeCustomRetention `admin.conversations.removeCustomRetention` API reference}. + */ + removeCustomRetention: bindApiCall(this, 'admin.conversations.removeCustomRetention'), + /** + * @description Rename a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.rename `admin.conversations.rename` API reference}. + */ + rename: bindApiCall(this, 'admin.conversations.rename'), + restrictAccess: { + /** + * @description Add an allowlist of IDP groups for accessing a channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.addGroup `admin.conversations.restrictAccess.addGroup` API reference}. + */ + addGroup: bindApiCall(this, 'admin.conversations.restrictAccess.addGroup'), + /** + * @description List all IDP Groups linked to a channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.listGroups `admin.conversations.restrictAccess.listGroups` API reference}. + */ + listGroups: bindApiCall(this, 'admin.conversations.restrictAccess.listGroups'), + /** + * @description Remove a linked IDP group linked from a private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.removeGroup `admin.conversations.restrictAccess.removeGroup` API reference}. + */ + removeGroup: bindApiCall(this, 'admin.conversations.restrictAccess.removeGroup'), + }, + /** + * @description Search for public or private channels in an Enterprise organization. + * @see {@link https://api.slack.com/methods/admin.conversations.search `admin.conversations.search` API reference}. + */ + search: bindApiCallWithOptionalArgument(this, 'admin.conversations.search'), + /** + * @description Set the posting permissions for a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.setConversationPrefs `admin.conversations.setConversationPrefs` API reference}. + */ + setConversationPrefs: bindApiCall(this, 'admin.conversations.setConversationPrefs'), + /** + * @description Set a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.setCustomRetention `admin.conversations.setCustomRetention` API reference}. + */ + setCustomRetention: bindApiCall(this, 'admin.conversations.setCustomRetention'), + /** + * @description Set the workspaces in an Enterprise grid org that connect to a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.setTeams `admin.conversations.setTeams` API reference}. + */ + setTeams: bindApiCall(this, 'admin.conversations.setTeams'), + /** + * @description Unarchive a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.unarchive `admin.conversations.unarchive` API reference}. + */ + unarchive: bindApiCall(this, 'admin.conversations.unarchive'), + }, + emoji: { + /** + * @description Add an emoji. + * @see {@link https://api.slack.com/methods/admin.emoji.add `admin.emoji.add` API reference}. + */ + add: bindApiCall(this, 'admin.emoji.add'), + /** + * @description Add an emoji alias. + * @see {@link https://api.slack.com/methods/admin.emoji.addAlias `admin.emoji.addAlias` API reference}. + */ + addAlias: bindApiCall(this, 'admin.emoji.addAlias'), + /** + * @description List emoji for an Enterprise Grid organization. + * @see {@link https://api.slack.com/methods/admin.emoji.list `admin.emoji.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'admin.emoji.list'), + /** + * @description Remove an emoji across an Enterprise Grid organization. + * @see {@link https://api.slack.com/methods/admin.emoji.remove `admin.emoji.remove` API reference}. + */ + remove: bindApiCall(this, 'admin.emoji.remove'), + /** + * @description Rename an emoji. + * @see {@link https://api.slack.com/methods/admin.emoji.rename `admin.emoji.rename` API reference}. + */ + rename: bindApiCall(this, 'admin.emoji.rename'), + }, + functions: { + /** + * @description Look up functions by a set of apps. + * @see {@link https://api.slack.com/methods/admin.functions.list `admin.functions.list` API reference}. + */ + list: bindApiCall(this, 'admin.functions.list'), + permissions: { + /** + * @description Lookup the visibility of multiple Slack functions and include the users if + * it is limited to particular named entities. + * @see {@link https://api.slack.com/methods/admin.functions.permissions.lookup `admin.functions.permissions.lookup` API reference}. + */ + lookup: bindApiCall(this, 'admin.functions.permissions.lookup'), + /** + * @description Set the visibility of a Slack function and define the users or workspaces if + * it is set to named_entities. + * @see {@link https://api.slack.com/methods/admin.functions.permissions.set `admin.functions.permissions.set` API reference}. + */ + set: bindApiCall(this, 'admin.functions.permissions.set'), + }, + }, + inviteRequests: { + /** + * @description Approve a workspace invite request. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.approve `admin.inviteRequests.approve` API reference}. + */ + approve: bindApiCall(this, 'admin.inviteRequests.approve'), + approved: { + /** + * @description List all approved workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.approved.list `admin.inviteRequests.approved.list` API reference}. + */ + list: bindApiCall(this, 'admin.inviteRequests.approved.list'), + }, + denied: { + /** + * @description List all denied workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.denied.list `admin.inviteRequests.denied.list` API reference}. + */ + list: bindApiCall(this, 'admin.inviteRequests.denied.list'), + }, + /** + * @description Deny a workspace invite request. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.deny `admin.inviteRequests.deny` API reference}. + */ + deny: bindApiCall(this, 'admin.inviteRequests.deny'), + /** + * @description List all pending workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.list `admin.inviteRequests.list` API reference}. + */ + list: bindApiCall(this, 'admin.inviteRequests.list'), + }, + roles: { + /** + * @description Adds members to the specified role with the specified scopes. + * @see {@link https://api.slack.com/methods/admin.roles.addAssignments `admin.roles.addAssignments` API reference}. + */ + addAssignments: bindApiCall(this, 'admin.roles.addAssignments'), + /** + * @description Lists assignments for all roles across entities. + * Options to scope results by any combination of roles or entities. + * @see {@link https://api.slack.com/methods/admin.roles.listAssignments `admin.roles.listAssignments` API reference}. + */ + listAssignments: bindApiCallWithOptionalArgument(this, 'admin.roles.listAssignments'), + /** + * @description Removes a set of users from a role for the given scopes and entities. + * @see {@link https://api.slack.com/methods/admin.roles.removeAssignments `admin.roles.removeAssignments` API reference}. + */ + removeAssignments: bindApiCall(this, 'admin.roles.removeAssignments'), + }, + teams: { + admins: { + /** + * @description List all of the admins on a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.admins.list `admin.teams.admins.list` API reference}. + */ + list: bindApiCall(this, 'admin.teams.admins.list'), + }, + /** + * @description Create an Enterprise team. + * @see {@link https://api.slack.com/methods/admin.teams.create `admin.teams.create` API reference}. + */ + create: bindApiCall(this, 'admin.teams.create'), + /** + * @description List all teams on an Enterprise organization. + * @see {@link https://api.slack.com/methods/admin.teams.list `admin.teams.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'admin.teams.list'), + owners: { + /** + * @description List all of the owners on a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. + */ + list: bindApiCall(this, 'admin.teams.owners.list'), + }, + settings: { + /** + * @description Fetch information about settings in a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. + */ + info: bindApiCall(this, 'admin.teams.settings.info'), + /** + * @description Set the default channels of a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDefaultChannels `admin.teams.settings.setDefaultChannels` API reference}. + */ + setDefaultChannels: bindApiCall(this, 'admin.teams.settings.setDefaultChannels'), + /** + * @description Set the description of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDescription `admin.teams.settings.setDescription` API reference}. + */ + setDescription: bindApiCall(this, 'admin.teams.settings.setDescription'), + /** + * @description Set the discoverability of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDiscoverability `admin.teams.settings.setDiscoverability` API reference}. + */ + setDiscoverability: bindApiCall(this, 'admin.teams.settings.setDiscoverability'), + /** + * @description Sets the icon of a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setIcon `admin.teams.settings.setIcon` API reference}. + */ + setIcon: bindApiCall(this, 'admin.teams.settings.setIcon'), + /** + * @description Set the name of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setName `admin.teams.settings.setName` API reference}. + */ + setName: bindApiCall(this, 'admin.teams.settings.setName'), + }, + }, + usergroups: { + /** + * @description Add up to one hundred default channels to an IDP group. + * @see {@link https://api.slack.com/methods/admin.usergroups.addChannels `admin.teams.usergroups.addChannels` API reference}. + */ + addChannels: bindApiCall(this, 'admin.usergroups.addChannels'), + /** + * @description Associate one or more default workspaces with an organization-wide IDP group. + * @see {@link https://api.slack.com/methods/admin.usergroups.addTeams `admin.teams.usergroups.addTeams` API reference}. + */ + addTeams: bindApiCall(this, 'admin.usergroups.addTeams'), + /** + * @description List the channels linked to an org-level IDP group (user group). + * @see {@link https://api.slack.com/methods/admin.usergroups.listChannels `admin.teams.usergroups.listChannels` API reference}. + */ + listChannels: bindApiCall(this, 'admin.usergroups.listChannels'), + /** + * @description Remove one or more default channels from an org-level IDP group (user group). + * @see {@link https://api.slack.com/methods/admin.usergroups.removeChannels `admin.teams.usergroups.removeChannels` API reference}. + */ + removeChannels: bindApiCall(this, 'admin.usergroups.removeChannels'), + }, + users: { + /** + * @description Add an Enterprise user to a workspace. + * @see {@link https://api.slack.com/methods/admin.users.assign `admin.users.assign` API reference}. + */ + assign: bindApiCall(this, 'admin.users.assign'), + /** + * @description Invite a user to a workspace. + * @see {@link https://api.slack.com/methods/admin.users.invite `admin.users.invite` API reference}. + */ + invite: bindApiCall(this, 'admin.users.invite'), + /** + * @description List users on a workspace. + * @see {@link https://api.slack.com/methods/admin.users.list `admin.users.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'admin.users.list'), + /** + * @description Remove a user from a workspace. + * @see {@link https://api.slack.com/methods/admin.users.remove `admin.users.remove` API reference}. + */ + remove: bindApiCall(this, 'admin.users.remove'), + session: { + /** + * @description Clear user-specific session settings—the session duration and what happens when the client + * closes—for a list of users. + * @see {@link https://api.slack.com/methods/admin.users.session.clearSettings `admin.users.session.clearSettings` API reference}. + */ + clearSettings: bindApiCall(this, 'admin.users.session.clearSettings'), + /** + * @description Get user-specific session settings—the session duration and what happens when the client + * closes—given a list of users. + * @see {@link https://api.slack.com/methods/admin.users.session.getSettings `admin.users.session.getSettings` API reference}. + */ + getSettings: bindApiCall(this, 'admin.users.session.getSettings'), + /** + * @description Revoke a single session for a user. The user will be forced to login to Slack. + * @see {@link https://api.slack.com/methods/admin.users.session.invalidate `admin.users.session.invalidate` API reference}. + */ + invalidate: bindApiCall(this, 'admin.users.session.invalidate'), + /** + * @description List active user sessions for an organization. + * @see {@link https://api.slack.com/methods/admin.users.session.list `admin.users.session.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'admin.users.session.list'), + /** + * @description Wipes all valid sessions on all devices for a given user. + * @see {@link https://api.slack.com/methods/admin.users.session.reset `admin.users.session.reset` API reference}. + */ + reset: bindApiCall(this, 'admin.users.session.reset'), + /** + * @description Enqueues an asynchronous job to wipe all valid sessions on all devices for a given user list. + * @see {@link https://api.slack.com/methods/admin.users.session.resetBulk `admin.users.session.resetBulk` API reference}. + */ + resetBulk: bindApiCall(this, 'admin.users.session.resetBulk'), + /** + * @description Configure the user-level session settings—the session duration and what happens when the client + * closes—for one or more users. + * @see {@link https://api.slack.com/methods/admin.users.session.setSettings `admin.users.session.setSettings` API reference}. + */ + setSettings: bindApiCall(this, 'admin.users.session.setSettings'), + }, + /** + * @description Set an existing guest, regular user, or owner to be an admin user. + * @see {@link https://api.slack.com/methods/admin.users.setAdmin `admin.users.setAdmin` API reference}. + */ + setAdmin: bindApiCall(this, 'admin.users.setAdmin'), + /** + * @description Set an expiration for a guest user. + * @see {@link https://api.slack.com/methods/admin.users.setExpiration `admin.users.setExpiration` API reference}. + */ + setExpiration: bindApiCall(this, 'admin.users.setExpiration'), + /** + * @description Set an existing guest, regular user, or admin user to be a workspace owner. + * @see {@link https://api.slack.com/methods/admin.users.setOwner `admin.users.setOwner` API reference}. + */ + setOwner: bindApiCall(this, 'admin.users.setOwner'), + /** + * @description Set an existing guest user, admin user, or owner to be a regular user. + * @see {@link https://api.slack.com/methods/admin.users.setRegular `admin.users.setRegular` API reference}. + */ + setRegular: bindApiCall(this, 'admin.users.setRegular'), + unsupportedVersions: { + /** + * @description Ask Slackbot to send you an export listing all workspace members using unsupported software, + * presented as a zipped CSV file. + * @see {@link https://api.slack.com/methods/admin.users.unsupportedVersions.export `admin.users.unsupportedVersions.export` API reference}. + */ + export: bindApiCall(this, 'admin.users.unsupportedVersions.export'), + }, + }, + workflows: { + collaborators: { + /** + * @description Add collaborators to workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.add `admin.workflows.collaborators.add` API reference}. + */ + add: bindApiCall(this, 'admin.workflows.collaborators.add'), + /** + * @description Remove collaborators from workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.remove `admin.workflows.collaborators.remove` API reference}. + */ + remove: bindApiCall(this, 'admin.workflows.collaborators.remove'), + }, + permissions: { + /** + * @description Look up the permissions for a set of workflows. + * @see {@link https://api.slack.com/methods/admin.workflows.permissions.lookup `admin.workflows.permissions.lookup` API reference}. + */ + lookup: bindApiCall(this, 'admin.workflows.permissions.lookup'), + }, + /** + * @description Search workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.search `admin.workflows.search` API reference}. + */ + search: bindApiCallWithOptionalArgument(this, 'admin.workflows.search'), + /** + * @description Unpublish workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.unpublish `admin.workflows.unpublish` API reference}. + */ + unpublish: bindApiCall(this, 'admin.workflows.unpublish'), + }, + }; + this.api = { + /** + * @description Checks API calling code. + * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. + */ + test: bindApiCallWithOptionalArgument(this, 'api.test'), + }; + this.assistant = { + threads: { + /** + * @description Set loading status to indicate that the app is building a response. + * @see {@link https://api.slack.com/methods/assistant.threads.setStatus `assistant.threads.setStatus` API reference}. + */ + setStatus: bindApiCall(this, 'assistant.threads.setStatus'), + /** + * @description Set suggested prompts for the user. Can suggest up to four prompts. + * @see {@link https://api.slack.com/methods/assistant.threads.setSuggestedPrompts `assistant.threads.setSuggestedPrompts` API reference}. + */ + setSuggestedPrompts: bindApiCall(this, 'assistant.threads.setSuggestedPrompts'), + /** + * @description Set the title of the thread. This is shown when a user views the app's chat history. + * @see {@link https://api.slack.com/methods/assistant.threads.setTitle `assistant.threads.setTitle` API reference}. + */ + setTitle: bindApiCall(this, 'assistant.threads.setTitle'), + }, + }; + this.apps = { + connections: { + /** + * @description Generate a temporary Socket Mode WebSocket URL that your app can connect to in order to receive + * events and interactive payloads over. + * @see {@link https://api.slack.com/methods/apps.connections.open `apps.connections.open` API reference}. + */ + open: bindApiCallWithOptionalArgument(this, 'apps.connections.open'), + }, + event: { + authorizations: { + /** + * @description Get a list of authorizations for the given event context. + * Each authorization represents an app installation that the event is visible to. + * @see {@link https://api.slack.com/methods/apps.event.authorizations.list `apps.event.authorizations.list` API reference}. + */ + list: bindApiCall(this, 'apps.event.authorizations.list'), + }, + }, + manifest: { + /** + * @description Create an app from an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.create `apps.manifest.create` API reference}. + */ + create: bindApiCall(this, 'apps.manifest.create'), + /** + * @description Permanently deletes an app created through app manifests. + * @see {@link https://api.slack.com/methods/apps.manifest.delete `apps.manifest.delete` API reference}. + */ + delete: bindApiCall(this, 'apps.manifest.delete'), + /** + * @description Export an app manifest from an existing app. + * @see {@link https://api.slack.com/methods/apps.manifest.export `apps.manifest.export` API reference}. + */ + export: bindApiCall(this, 'apps.manifest.export'), + /** + * @description Update an app from an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.update `apps.manifest.update` API reference}. + */ + update: bindApiCall(this, 'apps.manifest.update'), + /** + * @description Validate an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.validate `apps.manifest.validate` API reference}. + */ + validate: bindApiCall(this, 'apps.manifest.validate'), + }, + /** + * @description Uninstalls your app from a workspace. + * @see {@link https://api.slack.com/methods/apps.uninstall `apps.uninstall` API reference}. + */ + uninstall: bindApiCall(this, 'apps.uninstall'), + }; + this.auth = { + /** + * @description Revokes a token. + * @see {@link https://api.slack.com/methods/auth.revoke `auth.revoke` API reference}. + */ + revoke: bindApiCallWithOptionalArgument(this, 'auth.revoke'), + teams: { + /** + * @description Obtain a full list of workspaces your org-wide app has been approved for. + * @see {@link https://api.slack.com/methods/auth.teams.list `auth.teams.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'auth.teams.list'), + }, + test: bindApiCallWithOptionalArgument(this, 'auth.test'), + }; + this.bookmarks = { + /** + * @description Add bookmark to a channel. + * @see {@link https://api.slack.com/methods/bookmarks.add `bookmarks.add` API reference}. + */ + add: bindApiCall(this, 'bookmarks.add'), + /** + * @description Edit bookmark. + * @see {@link https://api.slack.com/methods/bookmarks.edit `bookmarks.edit` API reference}. + */ + edit: bindApiCall(this, 'bookmarks.edit'), + /** + * @description List bookmarks for a channel. + * @see {@link https://api.slack.com/methods/bookmarks.list `bookmarks.list` API reference}. + */ + list: bindApiCall(this, 'bookmarks.list'), + /** + * @description Remove bookmark from a channel. + * @see {@link https://api.slack.com/methods/bookmarks.remove `bookmarks.remove` API reference}. + */ + remove: bindApiCall(this, 'bookmarks.remove'), + }; + this.bots = { + /** + * @description Gets information about a bot user. + * @see {@link https://api.slack.com/methods/bots.info `bots.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, 'bots.info'), + }; + this.calls = { + /** + * @description Registers a new Call. + * @see {@link https://api.slack.com/methods/calls.add `calls.add` API reference}. + */ + add: bindApiCall(this, 'calls.add'), + /** + * @description Ends a Call. + * @see {@link https://api.slack.com/methods/calls.end `calls.end` API reference}. + */ + end: bindApiCall(this, 'calls.end'), + /** + * @description Returns information about a Call. + * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. + */ + info: bindApiCall(this, 'calls.info'), + /** + * @description Updates information about a Call. + * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. + */ + update: bindApiCall(this, 'calls.update'), + participants: { + /** + * @description Registers new participants added to a Call. + * @see {@link https://api.slack.com/methods/calls.participants.add `calls.participants.add` API reference}. + */ + add: bindApiCall(this, 'calls.participants.add'), + remove: bindApiCall(this, 'calls.participants.remove'), + }, + }; + this.canvases = { + access: { + /** + * @description Remove access to a canvas for specified entities. + * @see {@link https://api.slack.com/methods/canvases.access.delete `canvases.access.delete` API reference}. + */ + delete: bindApiCall(this, 'canvases.access.delete'), + /** + * @description Sets the access level to a canvas for specified entities. + * @see {@link https://api.slack.com/methods/canvases.access.set `canvases.access.set` API reference}. + */ + set: bindApiCall(this, 'canvases.access.set'), + }, + /** + * @description Create Canvas for a user. + * @see {@link https://api.slack.com/methods/canvases.create `canvases.create` API reference}. + */ + create: bindApiCallWithOptionalArgument(this, 'canvases.create'), + /** + * @description Deletes a canvas. + * @see {@link https://api.slack.com/methods/canvases.delete `canvases.delete` API reference}. + */ + delete: bindApiCall(this, 'canvases.delete'), + /** + * @description Update an existing canvas. + * @see {@link https://api.slack.com/methods/canvases.edit `canvases.edit` API reference}. + */ + edit: bindApiCall(this, 'canvases.edit'), + sections: { + /** + * @description Find sections matching the provided criteria. + * @see {@link https://api.slack.com/methods/canvases.sections.lookup `canvases.sections.lookup` API reference}. + */ + lookup: bindApiCall(this, 'canvases.sections.lookup'), + }, + }; + this.chat = { + /** + * @description Deletes a message. + * @see {@link https://api.slack.com/methods/chat.delete `chat.delete` API reference}. + */ + delete: bindApiCall(this, 'chat.delete'), + /** + * @description Deletes a pending scheduled message from the queue. + * @see {@link https://api.slack.com/methods/chat.deleteScheduledMessage `chat.deleteScheduledMessage` API reference}. + */ + deleteScheduledMessage: bindApiCall(this, 'chat.deleteScheduledMessage'), + /** + * @description Retrieve a permalink URL for a specific extant message. + * @see {@link https://api.slack.com/methods/chat.getPermalink `chat.getPermalink` API reference}. + */ + getPermalink: bindApiCall(this, 'chat.getPermalink'), + /** + * @description Share a me message into a channel. + * @see {@link https://api.slack.com/methods/chat.meMessage `chat.meMessage` API reference}. + */ + meMessage: bindApiCall(this, 'chat.meMessage'), + /** + * @description Sends an ephemeral message to a user in a channel. + * @see {@link https://api.slack.com/methods/chat.postEphemeral `chat.postEphemeral` API reference}. + */ + postEphemeral: bindApiCall(this, 'chat.postEphemeral'), + /** + * @description Sends a message to a channel. + * @see {@link https://api.slack.com/methods/chat.postMessage `chat.postMessage` API reference}. + */ + postMessage: bindApiCall(this, 'chat.postMessage'), + /** + * @description Schedules a message to be sent to a channel. + * @see {@link https://api.slack.com/methods/chat.scheduleMessage `chat.scheduleMessage` API reference}. + */ + scheduleMessage: bindApiCall(this, 'chat.scheduleMessage'), + scheduledMessages: { + /** + * @description Returns a list of scheduled messages. + * @see {@link https://api.slack.com/methods/chat.scheduledMessages.list `chat.scheduledMessages.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'chat.scheduledMessages.list'), + }, + /** + * @description Provide custom unfurl behavior for user-posted URLs. + * @see {@link https://api.slack.com/methods/chat.unfurl `chat.unfurl` API reference}. + */ + unfurl: bindApiCall(this, 'chat.unfurl'), + /** + * @description Updates a message. + * @see {@link https://api.slack.com/methods/chat.update `chat.update` API reference}. + */ + update: bindApiCall(this, 'chat.update'), + }; + this.conversations = { + /** + * @description Accepts an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.acceptSharedInvite `conversations.acceptSharedInvite` API reference}. + */ + acceptSharedInvite: bindApiCall(this, 'conversations.acceptSharedInvite'), + /** + * @description Approves an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.approveSharedInvite `conversations.approveSharedInvite` API reference}. + */ + approveSharedInvite: bindApiCall(this, 'conversations.approveSharedInvite'), + /** + * @description Archives a conversation. + * @see {@link https://api.slack.com/methods/conversations.archive `conversations.archive` API reference}. + */ + archive: bindApiCall(this, 'conversations.archive'), + canvases: { + /** + * @description Create a Channel Canvas for a channel. + * @see {@link https://api.slack.com/methods/conversations.canvases.create `conversations.canvases.create` API reference}. + */ + create: bindApiCall(this, 'conversations.canvases.create'), + }, + /** + * @description Closes a direct message or multi-person direct message. + * @see {@link https://api.slack.com/methods/conversations.close `conversations.close` API reference}. + */ + close: bindApiCall(this, 'conversations.close'), + /** + * @description Initiates a public or private channel-based conversation. + * @see {@link https://api.slack.com/methods/conversations.create `conversations.create` API reference}. + */ + create: bindApiCall(this, 'conversations.create'), + /** + * @description Declines an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.declineSharedInvite `conversations.declineSharedInvite` API reference}. + */ + declineSharedInvite: bindApiCall(this, 'conversations.declineSharedInvite'), + externalInvitePermissions: { + /** + * @description Convert a team in a shared channel from an External Limited channel to a fully shared Slack + * Connect channel or vice versa. + * @see {@link https://api.slack.com/methods/conversations.externalInvitePermissions.set `conversations.externalInvitePermissions.set` API reference}. + */ + set: bindApiCall(this, 'conversations.externalInvitePermissions.set'), + }, + /** + * @description Fetches a conversation's history of messages and events. + * @see {@link https://api.slack.com/methods/conversations.history `conversations.history` API reference}. + */ + history: bindApiCall(this, 'conversations.history'), + /** + * @description Retrieve information about a conversation. + * @see {@link https://api.slack.com/methods/conversations.info `conversations.info` API reference}. + */ + info: bindApiCall(this, 'conversations.info'), + /** + * @description Invites users to a channel. + * @see {@link https://api.slack.com/methods/conversations.invite `conversations.invite` API reference}. + */ + invite: bindApiCall(this, 'conversations.invite'), + /** + * @description Sends an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.inviteShared `conversations.inviteShared` API reference}. + */ + inviteShared: bindApiCall(this, 'conversations.inviteShared'), + /** + * @description Joins an existing conversation. + * @see {@link https://api.slack.com/methods/conversations.join `conversations.join` API reference}. + */ + join: bindApiCall(this, 'conversations.join'), + /** + * @description Removes a user from a conversation. + * @see {@link https://api.slack.com/methods/conversations.kick `conversations.kick` API reference}. + */ + kick: bindApiCall(this, 'conversations.kick'), + /** + * @description Leaves a conversation. + * @see {@link https://api.slack.com/methods/conversations.leave `conversations.leave` API reference}. + */ + leave: bindApiCall(this, 'conversations.leave'), + /** + * @description List all channels in a Slack team. + * @see {@link https://api.slack.com/methods/conversations.list `conversations.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'conversations.list'), + /** + * @description Lists shared channel invites that have been generated or received but have not been approved by + * all parties. + * @see {@link https://api.slack.com/methods/conversations.listConnectInvites `conversations.listConnectInvites` API reference}. + */ + listConnectInvites: bindApiCallWithOptionalArgument(this, 'conversations.listConnectInvites'), + /** + * @description Sets the read cursor in a channel. + * @see {@link https://api.slack.com/methods/conversations.mark `conversations.mark` API reference}. + */ + mark: bindApiCall(this, 'conversations.mark'), + /** + * @description Retrieve members of a conversation. + * @see {@link https://api.slack.com/methods/conversations.members `conversations.members` API reference}. + */ + members: bindApiCall(this, 'conversations.members'), + /** + * @description Opens or resumes a direct message or multi-person direct message. + * @see {@link https://api.slack.com/methods/conversations.open `conversations.open` API reference}. + */ + open: bindApiCall(this, 'conversations.open'), + /** + * @description Renames a conversation. + * @see {@link https://api.slack.com/methods/conversations.rename `conversations.rename` API reference}. + */ + rename: bindApiCall(this, 'conversations.rename'), + /** + * @description Retrieve a thread of messages posted to a conversation. + * @see {@link https://api.slack.com/methods/conversations.replies `conversations.replies` API reference}. + */ + replies: bindApiCall(this, 'conversations.replies'), + requestSharedInvite: { + /** + * @description Approves a request to add an external user to a channel and sends them a Slack Connect invite. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.approve `conversations.requestSharedInvite.approve` API reference}. + */ + approve: bindApiCall(this, 'conversations.requestSharedInvite.approve'), + /** + * @description Denies a request to invite an external user to a channel. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.deny `conversations.requestSharedInvite.deny` API reference}. + */ + deny: bindApiCall(this, 'conversations.requestSharedInvite.deny'), + }, + /** + * @description Sets the purpose for a conversation. + * @see {@link https://api.slack.com/methods/conversations.setPurpose `conversations.setPurpose` API reference}. + */ + setPurpose: bindApiCall(this, 'conversations.setPurpose'), + /** + * @description Sets the topic for a conversation. + * @see {@link https://api.slack.com/methods/conversations.setTopic `conversations.setTopic` API reference}. + */ + setTopic: bindApiCall(this, 'conversations.setTopic'), + /** + * @description Reverses conversation archival. + * @see {@link https://api.slack.com/methods/conversations.unarchive `conversations.unarchive` API reference}. + */ + unarchive: bindApiCall(this, 'conversations.unarchive'), + }; + this.dialog = { + /** + * @description Open a dialog with a user. + * @see {@link https://api.slack.com/methods/dialog.open `dialog.open` API reference}. + */ + open: bindApiCall(this, 'dialog.open'), + }; + this.dnd = { + /** + * @description Ends the current user's Do Not Disturb session immediately. + * @see {@link https://api.slack.com/methods/dnd.endDnd `dnd.endDnd` API reference}. + */ + endDnd: bindApiCallWithOptionalArgument(this, 'dnd.endDnd'), + /** + * @description Ends the current user's snooze mode immediately. + * @see {@link https://api.slack.com/methods/dnd.endSnooze `dnd.endSnooze` API reference}. + */ + endSnooze: bindApiCallWithOptionalArgument(this, 'dnd.endSnooze'), + /** + * @description Retrieves a user's current Do Not Disturb status. + * @see {@link https://api.slack.com/methods/dnd.info `dnd.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, 'dnd.info'), + /** + * @description Turns on Do Not Disturb mode for the current user, or changes its duration. + * @see {@link https://api.slack.com/methods/dnd.setSnooze `dnd.setSnooze` API reference}. + */ + setSnooze: bindApiCall(this, 'dnd.setSnooze'), + /** + * @description Retrieves the Do Not Disturb status for up to 50 users on a team. + * @see {@link https://api.slack.com/methods/dnd.teamInfo `dnd.teamInfo` API reference}. + */ + teamInfo: bindApiCall(this, 'dnd.teamInfo'), + }; + this.emoji = { + /** + * @description Lists custom emoji for a team. + * @see {@link https://api.slack.com/methods/emoji.list `emoji.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'emoji.list'), + }; + this.files = { + /** + * @description Finishes an upload started with {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal`}. + * @see {@link https://api.slack.com/methods/files.completeUploadExternal `files.completeUploadExternal` API reference}. + */ + completeUploadExternal: bindApiCall(this, 'files.completeUploadExternal'), + /** + * @description Deletes a file. + * @see {@link https://api.slack.com/methods/files.delete `files.delete` API reference}. + */ + delete: bindApiCall(this, 'files.delete'), + /** + * @description Gets a URL for an edge external file upload. + * @see {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal` API reference}. + */ + getUploadURLExternal: bindApiCall(this, 'files.getUploadURLExternal'), + /** + * @description Gets information about a file. + * @see {@link https://api.slack.com/methods/files.info `files.info` API reference}. + */ + info: bindApiCall(this, 'files.info'), + /** + * @description List files for a team, in a channel, or from a user with applied filters. + * @see {@link https://api.slack.com/methods/files.list `files.list` API reference}. + */ + list: bindApiCall(this, 'files.list'), + /** + * @description Revokes public/external sharing access for a file. + * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. + */ + revokePublicURL: bindApiCall(this, 'files.revokePublicURL'), + /** + * @description Enables a file for public/external sharing. + * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. + */ + sharedPublicURL: bindApiCall(this, 'files.sharedPublicURL'), + /** + * @description Uploads or creates a file. + * @deprecated Use `uploadV2` instead. See {@link https://api.slack.com/changelog/2024-04-a-better-way-to-upload-files-is-here-to-stay our post on retiring `files.upload`}. + * @see {@link https://api.slack.com/methods/files.upload `files.upload` API reference}. + */ + upload: bindApiCall(this, 'files.upload'), + /** + * @description Custom method to support a new way of uploading files to Slack. + * Supports a single file upload + * Supply: + * - (required) single file or content + * - (optional) channel, alt_text, snippet_type, + * Supports multiple file uploads + * Supply: + * - multiple upload_files + * Will try to honor both single file or content data supplied as well + * as multiple file uploads property. + * @see {@link https://slack.dev/node-slack-sdk/web-api#upload-a-file `@slack/web-api` Upload a file documentation}. + */ + uploadV2: bindFilesUploadV2(this), + comments: { + /** + * @description Deletes an existing comment on a file. + * @see {@link https://api.slack.com/methods/files.comments.delete `files.comments.delete` API reference}. + */ + delete: bindApiCall(this, 'files.comments.delete'), + }, + remote: { + /** + * @description Adds a file from a remote service. + * @see {@link https://api.slack.com/methods/files.remote.add `files.remote.add` API reference}. + */ + add: bindApiCall(this, 'files.remote.add'), + /** + * @description Retrieve information about a remote file added to Slack. + * @see {@link https://api.slack.com/methods/files.remote.info `files.remote.info` API reference}. + */ + info: bindApiCall(this, 'files.remote.info'), + /** + * @description List remote files added to Slack. + * @see {@link https://api.slack.com/methods/files.remote.list `files.remote.list` API reference}. + */ + list: bindApiCall(this, 'files.remote.list'), + /** + * @description Remove a remote file. + * @see {@link https://api.slack.com/methods/files.remote.remove `files.remote.remove` API reference}. + */ + remove: bindApiCall(this, 'files.remote.remove'), + /** + * @description Share a remote file into a channel. + * @see {@link https://api.slack.com/methods/files.remote.share `files.remote.share` API reference}. + */ + share: bindApiCall(this, 'files.remote.share'), + /** + * @description Updates an existing remote file. + * @see {@link https://api.slack.com/methods/files.remote.update `files.remote.update` API reference}. + */ + update: bindApiCall(this, 'files.remote.update'), + }, + }; + this.functions = { + /** + * @description Signal the failure to execute a Custom Function. + * @see {@link https://api.slack.com/methods/functions.completeError `functions.completeError` API reference}. + */ + completeError: bindApiCall(this, 'functions.completeError'), + /** + * @description Signal the successful completion of a Custom Function. + * @see {@link https://api.slack.com/methods/functions.completeSuccess `functions.completeSuccess` API reference}. + */ + completeSuccess: bindApiCall(this, 'functions.completeSuccess'), + }; + this.migration = { + /** + * @description For Enterprise Grid workspaces, map local user IDs to global user IDs. + * @see {@link https://api.slack.com/methods/migration.exchange `migration.exchange` API reference}. + */ + exchange: bindApiCall(this, 'migration.exchange'), + }; + this.oauth = { + /** + * @description Exchanges a temporary OAuth verifier code for an access token. + * @deprecated This is a legacy method only used by classic Slack apps. Use `oauth.v2.access` for new Slack apps. + * @see {@link https://api.slack.com/methods/oauth.access `oauth.access` API reference}. + */ + access: bindApiCall(this, 'oauth.access'), + v2: { + /** + * @description Exchanges a temporary OAuth verifier code for an access token. + * @see {@link https://api.slack.com/methods/oauth.v2.access `oauth.v2.access` API reference}. + */ + access: bindApiCall(this, 'oauth.v2.access'), + /** + * @description Exchanges a legacy access token for a new expiring access token and refresh token. + * @see {@link https://api.slack.com/methods/oauth.v2.exchange `oauth.v2.exchange` API reference}. + */ + exchange: bindApiCall(this, 'oauth.v2.exchange'), + }, + }; + this.openid = { + connect: { + /** + * @description Exchanges a temporary OAuth verifier code for an access token for {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. + * @see {@link https://api.slack.com/methods/openid.connect.token `openid.connect.token` API reference}. + */ + token: bindApiCall(this, 'openid.connect.token'), + /** + * @description Get the identity of a user who has authorized {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. + * @see {@link https://api.slack.com/methods/openid.connect.userInfo `openid.connect.userInfo` API reference}. + */ + userInfo: bindApiCallWithOptionalArgument(this, 'openid.connect.userInfo'), + }, + }; + this.pins = { + /** + * @description Pins an item to a channel. + * @see {@link https://api.slack.com/methods/pins.add `pins.add` API reference}. + */ + add: bindApiCall(this, 'pins.add'), + /** + * @description Lists items pinned to a channel. + * @see {@link https://api.slack.com/methods/pins.list `pins.list` API reference}. + */ + list: bindApiCall(this, 'pins.list'), + /** + * @description Un-pins an item from a channel. + * @see {@link https://api.slack.com/methods/pins.remove `pins.remove` API reference}. + */ + remove: bindApiCall(this, 'pins.remove'), + }; + this.reactions = { + /** + * @description Adds a reaction to an item. + * @see {@link https://api.slack.com/methods/reactions.add `reactions.add` API reference}. + */ + add: bindApiCall(this, 'reactions.add'), + /** + * @description Gets reactions for an item. + * @see {@link https://api.slack.com/methods/reactions.get `reactions.get` API reference}. + */ + get: bindApiCall(this, 'reactions.get'), + /** + * @description List reactions made by a user. + * @see {@link https://api.slack.com/methods/reactions.list `reactions.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'reactions.list'), + /** + * @description Removes a reaction from an item. + * @see {@link https://api.slack.com/methods/reactions.remove `reactions.remove` API reference}. + */ + remove: bindApiCall(this, 'reactions.remove'), + }; + // TODO: keep tabs on reminders APIs, may be deprecated once Later list APIs land + // See: https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders + this.reminders = { + /** + * @description Creates a reminder. + * @see {@link https://api.slack.com/methods/reminders.add `reminders.add` API reference}. + */ + add: bindApiCall(this, 'reminders.add'), + /** + * @description Marks a reminder as complete. + * @see {@link https://api.slack.com/methods/reminders.complete `reminders.complete` API reference}. + */ + complete: bindApiCall(this, 'reminders.complete'), + /** + * @description Deletes a reminder. + * @see {@link https://api.slack.com/methods/reminders.delete `reminders.delete` API reference}. + */ + delete: bindApiCall(this, 'reminders.delete'), + /** + * @description Gets information about a reminder. + * @see {@link https://api.slack.com/methods/reminders.info `reminders.info` API reference}. + */ + info: bindApiCall(this, 'reminders.info'), + /** + * @description Lists all reminders created by or for a given user. + * @see {@link https://api.slack.com/methods/reminders.list `reminders.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'reminders.list'), + }; + this.rtm = { + /** + * @description Starts a Real Time Messaging session. + * @see {@link https://api.slack.com/methods/rtm.connect `rtm.connect` API reference}. + */ + connect: bindApiCallWithOptionalArgument(this, 'rtm.connect'), + /** + * @description Starts a Real Time Messaging session. + * @deprecated Use `rtm.connect` instead. See {@link https://api.slack.com/changelog/2021-10-rtm-start-to-stop our post on retiring `rtm.start`}. + * @see {@link https://api.slack.com/methods/rtm.start `rtm.start` API reference}. + */ + start: bindApiCallWithOptionalArgument(this, 'rtm.start'), + }; + this.search = { + /** + * @description Searches for messages and files matching a query. + * @see {@link https://api.slack.com/methods/search.all search.all` API reference}. + */ + all: bindApiCall(this, 'search.all'), + /** + * @description Searches for files matching a query. + * @see {@link https://api.slack.com/methods/search.files search.files` API reference}. + */ + files: bindApiCall(this, 'search.files'), + /** + * @description Searches for messages matching a query. + * @see {@link https://api.slack.com/methods/search.messages search.messages` API reference}. + */ + messages: bindApiCall(this, 'search.messages'), + }; + this.team = { + /** + * @description Gets the access logs for the current team. + * @see {@link https://api.slack.com/methods/team.accessLogs `team.accessLogs` API reference}. + */ + accessLogs: bindApiCallWithOptionalArgument(this, 'team.accessLogs'), + /** + * @description Gets billable users information for the current team. + * @see {@link https://api.slack.com/methods/team.billableInfo `team.billableInfo` API reference}. + */ + billableInfo: bindApiCallWithOptionalArgument(this, 'team.billableInfo'), + billing: { + /** + * @description Reads a workspace's billing plan information. + * @see {@link https://api.slack.com/methods/team.billing.info `team.billing.info` API reference}. + */ + info: bindApiCall(this, 'team.billing.info'), + }, + externalTeams: { + /** + * @description Disconnect an external organization. + * @see {@link https://api.slack.com/methods/team.externalTeams.disconnect `team.externalTeams.disconnect` API reference}. + */ + disconnect: bindApiCall(this, 'team.externalTeams.disconnect'), + /** + * @description Returns a list of all the external teams connected and details about the connection. + * @see {@link https://api.slack.com/methods/team.externalTeams.list `team.externalTeams.list` API reference}. + */ + list: bindApiCall(this, 'team.externalTeams.list'), + }, + /** + * @description Gets information about the current team. + * @see {@link https://api.slack.com/methods/team.info `team.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, 'team.info'), + /** + * @description Gets the integration logs for the current team. + * @see {@link https://api.slack.com/methods/team.integrationLogs `team.integrationLogs` API reference}. + */ + integrationLogs: bindApiCallWithOptionalArgument(this, 'team.integrationLogs'), + preferences: { + /** + * @description Retrieve a list of a workspace's team preferences. + * @see {@link https://api.slack.com/methods/team.preferences.list `team.preferences.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'team.preferences.list'), + }, + profile: { + /** + * @description Retrieve a team's profile. + * @see {@link https://api.slack.com/methods/team.profile.get `team.profile.get` API reference}. + */ + get: bindApiCallWithOptionalArgument(this, 'team.profile.get'), + }, + }; + this.tooling = { + tokens: { + /** + * @description Exchanges a refresh token for a new app configuration token. + * @see {@link https://api.slack.com/methods/tooling.tokens.rotate `tooling.tokens.rotate` API reference}. + */ + rotate: bindApiCall(this, 'tooling.tokens.rotate'), + }, + }; + this.usergroups = { + /** + * @description Create a User Group. + * @see {@link https://api.slack.com/methods/usergroups.create `usergroups.create` API reference}. + */ + create: bindApiCall(this, 'usergroups.create'), + /** + * @description Disable an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.disable `usergroups.disable` API reference}. + */ + disable: bindApiCall(this, 'usergroups.disable'), + /** + * @description Enable an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.enable `usergroups.enable` API reference}. + */ + enable: bindApiCall(this, 'usergroups.enable'), + /** + * @description List all User Groups for a team. + * @see {@link https://api.slack.com/methods/usergroups.list `usergroups.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, 'usergroups.list'), + /** + * @description Update an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.update `usergroups.update` API reference}. + */ + update: bindApiCall(this, 'usergroups.update'), + users: { + /** + * @description List all users in a User Group. + * @see {@link https://api.slack.com/methods/usergroups.users.list `usergroups.users.list` API reference}. + */ + list: bindApiCall(this, 'usergroups.users.list'), + /** + * @description Update the list of users in a User Group. + * @see {@link https://api.slack.com/methods/usergroups.users.update `usergroups.users.update` API reference}. + */ + update: bindApiCall(this, 'usergroups.users.update'), + }, + }; + this.users = { + /** + * @description List conversations the calling user may access. + * @see {@link https://api.slack.com/methods/users.conversations `users.conversations` API reference}. + */ + conversations: bindApiCall(this, 'users.conversations'), + /** + * @description Delete the user profile photo. + * @see {@link https://api.slack.com/methods/users.deletePhoto `users.deletePhoto` API reference}. + */ + deletePhoto: bindApiCall(this, 'users.deletePhoto'), + discoverableContacts: { + /** + * @description Lookup an email address to see if someone is on Slack. + * @see {@link https://api.slack.com/methods/users.discoverableContacts.lookup `users.discoverableContacts.lookup` API reference}. + */ + lookup: bindApiCall(this, 'users.discoverableContacts.lookup'), + }, + /** + * @description Gets user presence information. + * @see {@link https://api.slack.com/methods/users.getPresence `users.getPresence` API reference}. + */ + getPresence: bindApiCall(this, 'users.getPresence'), + /** + * @description Get a user's identity. + * @see {@link https://api.slack.com/methods/users.identity `users.identity` API reference}. + */ + identity: bindApiCall(this, 'users.identity'), + /** + * @description Gets information about a user. + * @see {@link https://api.slack.com/methods/users.info `users.info` API reference}. + */ + info: bindApiCall(this, 'users.info'), + /** + * @description Lists all users in a Slack team. + * @see {@link https://api.slack.com/methods/users.list `users.list` API reference}. + */ + list: bindApiCall(this, 'users.list'), + /** + * @description Find a user with an email address. + * @see {@link https://api.slack.com/methods/users.lookupByEmail `users.lookupByEmail` API reference}. + */ + lookupByEmail: bindApiCall(this, 'users.lookupByEmail'), + /** + * @description Set the user profile photo. + * @see {@link https://api.slack.com/methods/users.setPhoto `users.setPhoto` API reference}. + */ + setPhoto: bindApiCall(this, 'users.setPhoto'), + /** + * @description Manually sets user presence. + * @see {@link https://api.slack.com/methods/users.setPresence `users.setPresence` API reference}. + */ + setPresence: bindApiCall(this, 'users.setPresence'), + profile: { + /** + * @description Retrieve a user's profile information, including their custom status. + * @see {@link https://api.slack.com/methods/users.profile.get `users.profile.get` API reference}. + */ + get: bindApiCall(this, 'users.profile.get'), + /** + * @description Set a user's profile information, including custom status. + * @see {@link https://api.slack.com/methods/users.profile.set `users.profile.set` API reference}. + */ + set: bindApiCall(this, 'users.profile.set'), + }, + }; + this.views = { + /** + * @description Open a view for a user. + * @see {@link https://api.slack.com/methods/views.open `views.open` API reference}. + */ + open: bindApiCall(this, 'views.open'), + /** + * @description Publish a static view for a user. + * @see {@link https://api.slack.com/methods/views.publish `views.publish` API reference}. + */ + publish: bindApiCall(this, 'views.publish'), + /** + * @description Push a view onto the stack of a root view. + * @see {@link https://api.slack.com/methods/views.push `views.push` API reference}. + */ + push: bindApiCall(this, 'views.push'), + /** + * @description Update an existing view. + * @see {@link https://api.slack.com/methods/views.update `views.update` API reference}. + */ + update: bindApiCall(this, 'views.update'), + }; + // ------------------ + // Deprecated methods + // ------------------ + // TODO: breaking changes for future majors: + // - stars.* methods are marked as deprecated; once Later has APIs, these will see an official sunsetting timeline + // - workflows.* methods, Sep 12 2024: https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back + this.stars = { + /** + * @description Save an item for later. Formerly known as adding a star. + * @deprecated Stars can still be added but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.add `stars.add` API reference}. + */ + add: bindApiCall(this, 'stars.add'), + /** + * @description List a user's saved items, formerly known as stars. + * @deprecated Stars can still be listed but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.list `stars.list` API reference}. + */ + list: bindApiCall(this, 'stars.list'), + /** + * @description Remove a saved item from a user's saved items, formerly known as stars. + * @deprecated Stars can still be removed but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.remove `stars.remove` API reference}. + */ + remove: bindApiCall(this, 'stars.remove'), + }; + this.workflows = { + /** + * @description Indicate that an app's step in a workflow completed execution. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.stepCompleted `workflows.stepCompleted` API reference}. + */ + stepCompleted: bindApiCall(this, 'workflows.stepCompleted'), + /** + * @description Indicate that an app's step in a workflow failed to execute. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.stepFailed `workflows.stepFailed` API reference}. + */ + stepFailed: bindApiCall(this, 'workflows.stepFailed'), + /** + * @description Update the configuration for a workflow step. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.updateStep `workflows.updateStep` API reference}. + */ + updateStep: bindApiCall(this, 'workflows.updateStep'), + }; + // Check that the class being created extends from `WebClient` rather than this class + if (new.target !== WebClient_1.WebClient && !(new.target.prototype instanceof WebClient_1.WebClient)) { + throw new Error('Attempt to inherit from WebClient methods without inheriting from WebClient'); + } + } } +exports.Methods = Methods; +__exportStar(__nccwpck_require__(4775), exports); +//# sourceMappingURL=methods.js.map -module.exports = __nccwpck_require__(897)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), - -/***/ 897: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(744); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); +/***/ }), - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +/***/ 1766: +/***/ ((__unused_webpack_module, exports) => { - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +"use strict"; - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.rapidRetryPolicy = exports.fiveRetriesInFiveMinutes = exports.tenRetriesInAboutThirtyMinutes = void 0; +/** + * The default retry policy. Retry up to 10 times, over the span of about 30 minutes. It's not exact because + * randomization has been added to prevent a stampeding herd problem (if all instances in your application are retrying + * a request at the exact same intervals, they are more likely to cause failures for each other). + */ +exports.tenRetriesInAboutThirtyMinutes = { + retries: 10, + factor: 1.96821, + randomize: true, +}; +/** + * Short & sweet, five retries in five minutes and then bail. + */ +exports.fiveRetriesInFiveMinutes = { + retries: 5, + factor: 3.86, +}; +/** + * This policy is just to keep the tests running fast. + */ +exports.rapidRetryPolicy = { + minTimeout: 0, + maxTimeout: 1, +}; +const policies = { + tenRetriesInAboutThirtyMinutes: exports.tenRetriesInAboutThirtyMinutes, + fiveRetriesInFiveMinutes: exports.fiveRetriesInFiveMinutes, + rapidRetryPolicy: exports.rapidRetryPolicy, +}; +exports["default"] = policies; +//# sourceMappingURL=retry-policies.js.map - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +/***/ }), - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +/***/ 381: +/***/ ((__unused_webpack_module, exports) => { - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. +"use strict"; - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=index.js.map - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); +/***/ }), - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } +/***/ 5591: +/***/ ((__unused_webpack_module, exports) => { - return debug; - } +"use strict"; - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=index.js.map - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; +/***/ }), - createDebug.names = []; - createDebug.skips = []; +/***/ 1324: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +module.exports = +{ + parallel : __nccwpck_require__(3857), + serial : __nccwpck_require__(1054), + serialOrdered : __nccwpck_require__(3961) +}; - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - namespaces = split[i].replace(/\*/g, '.*?'); +/***/ }), - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } +/***/ 4818: +/***/ ((module) => { - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +// API +module.exports = abort; - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - let i; - let len; + // reset leftover jobs + state.jobs = {}; +} - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - return false; - } +/***/ }), - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +/***/ 8452: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } +var defer = __nccwpck_require__(9200); - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } +// API +module.exports = async; - createDebug.enable(createDebug.load()); +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; - return createDebug; -} + // check if async happened + defer(function() { isAsync = true; }); -module.exports = setup; + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} /***/ }), -/***/ 2830: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9200: +/***/ ((module) => { + +module.exports = defer; /** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(6110); -} else { - module.exports = __nccwpck_require__(5108); + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } } /***/ }), -/***/ 5108: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 4902: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Module dependencies. - */ +var async = __nccwpck_require__(8452) + , abort = __nccwpck_require__(4818) + ; -const tty = __nccwpck_require__(2018); -const util = __nccwpck_require__(9023); +// API +module.exports = iterate; /** - * This is the Node.js implementation of `debug()`. + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } -exports.colors = [6, 2, 3, 4, 5, 1]; + // clean up jobs + delete state.jobs[key]; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(1450); + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + // return salvaged results + callback(error, state.results); + }); } /** - * Build up the default `inspectOpts` object from the environment variables. + * Runs iterator over provided job element * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else */ +function runJob(iterator, key, item, callback) +{ + var aborter; -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } + return aborter; +} - obj[prop] = val; - return obj; -}, {}); -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ +/***/ }), -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} +/***/ 1721: +/***/ ((module) => { + +// API +module.exports = state; /** - * Adds ANSI color escape codes if enabled. + * Creates initial state object + * for iteration over list * - * @api public + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } + return initState; } -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ +/***/ }), -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} +/***/ 3351: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} +var abort = __nccwpck_require__(4818) + , async = __nccwpck_require__(8452) + ; + +// API +module.exports = terminator; /** - * Load `namespaces`. + * Terminates jobs in the attached state context * - * @return {String} returns the previously persisted debug modes - * @api private + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } -function load() { - return process.env.DEBUG; + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); } + +/***/ }), + +/***/ 3857: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var iterate = __nccwpck_require__(4902) + , initState = __nccwpck_require__(1721) + , terminator = __nccwpck_require__(3351) + ; + +// Public API +module.exports = parallel; + /** - * Init logic for `debug` instances. + * Runs iterator over provided array elements in parallel * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator */ +function parallel(list, iterator, callback) +{ + var state = initState(list); -function init(debug) { - debug.inspectOpts = {}; + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); } -module.exports = __nccwpck_require__(897)(exports); -const {formatters} = module.exports; +/***/ }), -/** - * Map %o to `util.inspect()`, all on a single line. - */ +/***/ 1054: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +var serialOrdered = __nccwpck_require__(3961); + +// Public API +module.exports = serial; /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} /***/ }), -/***/ 2710: +/***/ 3961: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Stream = (__nccwpck_require__(2203).Stream); -var util = __nccwpck_require__(9023); +var iterate = __nccwpck_require__(4902) + , initState = __nccwpck_require__(1721) + , terminator = __nccwpck_require__(3351) + ; -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } -DelayedStream.create = function(source, options) { - var delayedStream = new this(); + // done here + callback(null, state.results); + }); - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } + return terminator.bind(state, callback); +} - delayedStream.source = source; +/* + * -- Sort methods + */ - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} - return delayedStream; -}; -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); +/***/ }), -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; +/***/ 9380: +/***/ ((module) => { -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } +"use strict"; - this.source.resume(); -}; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; + var r = range(a, b, str); -DelayedStream.prototype.release = function() { - this._released = true; + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } - this._bufferedEvents.push(args); -}; + bi = str.indexOf(b, i + 1); + } -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } + i = ai < bi && ai >= 0 ? ai : bi; + } - if (this.dataSize <= this.maxDataSize) { - return; + if (begs.length) { + result = [ left, right ]; + } } - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + return result; +} /***/ }), -/***/ 2415: -/***/ ((module) => { - -"use strict"; +/***/ 4691: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var concatMap = __nccwpck_require__(7087); +var balanced = __nccwpck_require__(9380); -var has = Object.prototype.hasOwnProperty - , prefix = '~'; +module.exports = expandTop; -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); } - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; + parts.push.apply(parts, p); - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; + return parts; +} - return emitter; +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); } -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; +function identity(e) { + return e; } -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); } -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} - if (this._eventsCount === 0) return names; +function expand(str, isTop) { + var expansions = []; - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } } - return names; -}; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; + var N; - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); } - return ee; -}; + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; + return expansions; +} - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return false; +/***/ }), - var listeners = this._events[evt] - , len = arguments.length - , args - , i; +/***/ 5630: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); +var util = __nccwpck_require__(9023); +var Stream = (__nccwpck_require__(2203).Stream); +var DelayedStream = __nccwpck_require__(2710); - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } + this._handleErrors(stream); - listeners[i].fn.apply(listeners[i].context, args); - } + if (this.pauseStreams) { + stream.pause(); } } - return true; + this._streams.push(stream); + return this; }; -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; }; -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } }; -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; + + if (typeof stream == 'undefined') { + this.end(); + return; } - var listeners = this._events[evt]; + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); } - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; } - return this; + var value = stream; + this.write(value); + this._getNext(); }; -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; } - return this; + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); }; -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; -} +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; -/***/ }), +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; -/***/ 4778: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } -var debug; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __nccwpck_require__(2830)("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; } - debug.apply(null, arguments); }; +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; -/***/ }), - -/***/ 1573: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var url = __nccwpck_require__(7016); -var URL = url.URL; -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var Writable = (__nccwpck_require__(2203).Writable); -var assert = __nccwpck_require__(2613); -var debug = __nccwpck_require__(4778); +/***/ }), -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL()); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} +/***/ 7087: +/***/ ((module) => { -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", -]; +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; -// Error types with codes -var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError -); -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); -// istanbul ignore next -var destroy = Writable.prototype.destroy || noop; +/***/ }), -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; +/***/ 6110: +/***/ ((module, exports, __nccwpck_require__) => { - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } +/* eslint-env browser */ - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } - }; +/** + * This is the web browser implementation of `debug()`. + */ - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; -RedirectableRequest.prototype.abort = function () { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); -}; + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); -RedirectableRequest.prototype.destroy = function (error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; -}; +/** + * Colors. + */ -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; - // Validate input and shift parameters if necessary - if (!isString(data) && !isBuffer(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (isFunction(data)) { - callback = data; - data = encoding = null; - } - else if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; +/** + * Colorize log arguments if enabled. + * + * @api public + */ -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; + if (!this.useColors) { + return; + } - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } + args.splice(lastC, 0, c); +} - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - self.removeListener("close", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - return this; -}; + return r; +} -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } +module.exports = __nccwpck_require__(897)(exports); - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } +const {formatters} = module.exports; - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } }; -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } +/***/ }), - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } +/***/ 897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(744); + createDebug.destroy = destroy; -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. + /** + * The currently active debug mode names, and names to skip. + */ - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); + createDebug.names = []; + createDebug.skips = []; - // Clean up - this._requestBodyBuffers = []; - return; - } + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - // The response is a redirect, so abort the current request - destroyRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); + const self = debug; - // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - // Evaluate the beforeRedirect callback - if (isFunction(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - // Perform the redirected request - this._performRequest(); -}; + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); - } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); - } - else { - callback = options; - options = validateUrl(input); - input = { protocol: protocol }; - } - if (isFunction(options)) { - callback = options; - options = null; - } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString(options.host) && !isString(options.hostname)) { - options.hostname = "::1"; - } + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} + return debug; + } -function noop() { /* empty */ } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -function parseUrl(input) { - var parsed; - /* istanbul ignore else */ - if (useNativeURL) { - parsed = new URL(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; -function resolveUrl(relative, base) { - /* istanbul ignore next */ - return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); -} + createDebug.names = []; + createDebug.skips = []; -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); - } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; + namespaces = split[i].replace(/\*/g, '.*?'); - return spread; -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -function createErrorType(code, message, baseClass) { - // Create constructor - function CustomError(properties) { - Error.captureStackTrace(this, this.constructor); - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; - // Attach constructor and set default properties - CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); - return CustomError; -} + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop); - request.destroy(error); -} + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } -function isSubdomain(subdomain, domain) { - assert(isString(subdomain) && isString(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} + return false; + } -function isString(value) { - return typeof value === "string" || value instanceof String; -} + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } -function isFunction(value) { - return typeof value === "function"; -} + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -function isBuffer(value) { - return typeof value === "object" && ("length" in value); -} + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -function isURL(value) { - return URL && value instanceof URL; + createDebug.enable(createDebug.load()); + + return createDebug; } -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; +module.exports = setup; /***/ }), -/***/ 6454: +/***/ 2830: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var CombinedStream = __nccwpck_require__(5630); -var util = __nccwpck_require__(9023); -var path = __nccwpck_require__(6928); -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var parseUrl = (__nccwpck_require__(7016).parse); -var fs = __nccwpck_require__(9896); -var Stream = (__nccwpck_require__(2203).Stream); -var mime = __nccwpck_require__(4096); -var asynckit = __nccwpck_require__(1324); -var populate = __nccwpck_require__(1835); - -// Public API -module.exports = FormData; - -// make it a Stream -util.inherits(FormData, CombinedStream); - /** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(6110); +} else { + module.exports = __nccwpck_require__(5108); +} - CombinedStream.call(this); - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } -} +/***/ }), -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; +/***/ 5108: +/***/ ((module, exports, __nccwpck_require__) => { -FormData.prototype.append = function(field, value, options) { +/** + * Module dependencies. + */ - options = options || {}; +const tty = __nccwpck_require__(2018); +const util = __nccwpck_require__(9023); - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } +/** + * This is the Node.js implementation of `debug()`. + */ - var append = CombinedStream.prototype.append.bind(this); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } +/** + * Colors. + */ - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(1450); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - append(header); - append(value); - append(footer); +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - // pass along options.knownLength - this._trackLength(header, value, options); -}; + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; + obj[prop] = val; + return obj; +}, {}); - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - this._valueLength += valueLength; +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - // empty or either doesn't have path or not an http response or not a stream - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { - return; - } +function formatArgs(args) { + const {namespace: name, useColors} = this; - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; -FormData.prototype._lengthRetriever = function(value, callback) { + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} - if (value.hasOwnProperty('fd')) { +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} - var fileSize; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - if (err) { - callback(err); - return; - } +function load() { + return process.env.DEBUG; +} - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); +function init(debug) { + debug.inspectOpts = {}; - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - // something else - } else { - callback('Unknown stream'); - } -}; +module.exports = __nccwpck_require__(897)(exports); -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } +const {formatters} = module.exports; - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); +/** + * Map %o to `util.inspect()`, all on a single line. + */ - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - // skip nullish headers. - if (header == null) { - continue; - } - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } +/***/ }), - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } +/***/ 2710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; +var Stream = (__nccwpck_require__(2203).Stream); +var util = __nccwpck_require__(9023); -FormData.prototype._getContentDisposition = function(value, options) { +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; - var filename - , contentDisposition - ; + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } +DelayedStream.create = function(source, options) { + var delayedStream = new this(); - if (filename) { - contentDisposition = 'filename="' + filename + '"'; + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - return contentDisposition; -}; - -FormData.prototype._getContentType = function(value, options) { + delayedStream.source = source; - // use custom content-type above all - var contentType = options.contentType; + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); } - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } + return delayedStream; +}; - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; } +}); - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); } - return contentType; + this.source.resume(); }; -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } +DelayedStream.prototype.release = function() { + this._released = true; - next(footer); - }.bind(this); + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; }; -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; }; -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); } - return formHeaders; + this._bufferedEvents.push(args); }; -FormData.prototype.setBoundary = function(boundary) { - this._boundary = boundary; -}; +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); + if (this.dataSize <= this.maxDataSize) { + return; } - return this._boundary; + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); }; -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { +/***/ }), - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } +/***/ 2415: +/***/ ((module) => { - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); - } - } - } +"use strict"; - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); } - this._boundary = boundary; -}; + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; +} + +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; - return knownLength; -}; + if (this._eventsCount === 0) return names; -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } - if (this._valuesToMeasure.length) { - hasKnownLength = false; + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); } - return hasKnownLength; + return names; }; -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } - - values.forEach(function(length) { - knownLength += length; - }); - - cb(null, knownLength); - }); + return ee; }; -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; - - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; - // use custom params - } else { +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; - } - } + if (!this._events[evt]) return false; - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - // get content length and fire away - this.getLength(function(err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } - // add content length - if (length) { - request.setHeader('Content-Length', length); + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; } - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; - return cb.call(this, error, responce); - }; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - onResponse = callback.bind(this, null); + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } - request.on('error', callback); - request.on('response', onResponse); + listeners[i].fn.apply(listeners[i].context, args); + } } - }.bind(this)); - - return request; -}; - -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); } -}; -FormData.prototype.toString = function () { - return '[object FormData]'; + return true; }; - -/***/ }), - -/***/ 1835: -/***/ ((module) => { - -// populates missing values -module.exports = function(dst, src) { - - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); - - return dst; +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); }; - -/***/ }), - -/***/ 3813: -/***/ ((module) => { - -"use strict"; - - -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); }; +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; -/***/ }), + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } -/***/ 201: -/***/ ((module) => { + var listeners = this._events[evt]; -// https://github.com/electron/electron/issues/2288 -function isElectron() { - // Renderer process - if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') { - return true; + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); } - - // Main process - if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) { - return true; + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } } - // Detect the user agent when the `nodeIntegration` option is set to false - if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) { - return true; - } + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } - return false; -} + return this; +}; -module.exports = isElectron; +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } -/***/ }), + return this; +}; -/***/ 6543: -/***/ ((module) => { +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; -"use strict"; +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; -const isStream = stream => - stream !== null && - typeof stream === 'object' && - typeof stream.pipe === 'function'; +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; +} -isStream.writable = stream => - isStream(stream) && - stream.writable !== false && - typeof stream._write === 'function' && - typeof stream._writableState === 'object'; -isStream.readable = stream => - isStream(stream) && - stream.readable !== false && - typeof stream._read === 'function' && - typeof stream._readableState === 'object'; +/***/ }), -isStream.duplex = stream => - isStream.writable(stream) && - isStream.readable(stream); +/***/ 4778: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -isStream.transform = stream => - isStream.duplex(stream) && - typeof stream._transform === 'function'; +var debug; -module.exports = isStream; +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __nccwpck_require__(2830)("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; + } + } + debug.apply(null, arguments); +}; /***/ }), -/***/ 9829: +/***/ 1573: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - */ - -module.exports = __nccwpck_require__(1813) - - -/***/ }), +var url = __nccwpck_require__(7016); +var URL = url.URL; +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var Writable = (__nccwpck_require__(2203).Writable); +var assert = __nccwpck_require__(2613); +var debug = __nccwpck_require__(4778); -/***/ 4096: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Whether to use the native URL object or the legacy url module +var useNativeURL = false; +try { + assert(new URL()); +} +catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; +} -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +// URL fields to preserve in copy operations +var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash", +]; +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); +// Error types with codes +var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError +); +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); -/** - * Module dependencies. - * @private - */ +// istanbul ignore next +var destroy = Writable.prototype.destroy || noop; -var db = __nccwpck_require__(9829) -var extname = (__nccwpck_require__(6928).extname) +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; -/** - * Module variables. - * @private - */ + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + try { + self._processResponse(response); + } + catch (cause) { + self.emit("error", cause instanceof RedirectionError ? + cause : new RedirectionError({ cause: cause })); + } + }; -/** - * Module exports. - * @public - */ + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) +RedirectableRequest.prototype.abort = function () { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); +}; -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) +RedirectableRequest.prototype.destroy = function (error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; +}; -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } -function charset (type) { - if (!type || typeof type !== 'string') { - return false + // Validate input and shift parameters if necessary + if (!isString(data) && !isBuffer(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction(encoding)) { + callback = encoding; + encoding = null; } - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; - if (mime && mime.charset) { - return mime.charset +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (isFunction(data)) { + callback = data; + data = encoding = null; + } + else if (isFunction(encoding)) { + callback = encoding; + encoding = null; } - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; } +}; - return false -} +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); } - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } - if (!mime) { - return false + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; + } + + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + self.removeListener("close", clearTimer); + if (callback) { + self.removeListener("timeout", callback); + } + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); + } } - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() + // Attach callback if passed + if (callback) { + this.on("timeout", callback); } - return mime -} + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } + return this; +}; - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); - if (!exts || !exts.length) { - return false +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; } - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } -function lookup (path) { - if (!path || typeof path !== 'string') { - return false + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } } +}; - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - if (!extension) { - return false +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); } - return exports.types[extension] || false -} + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } -/** - * Populate the extensions and types maps. - * @private - */ + // Create the native request and set up its event handlers + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path; - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; - if (!exts || !exts.length) { - return - } +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } - // mime -> extensions - extensions[type] = exts + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) + // Clean up + this._requestBodyBuffers = []; + return; + } - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } + // The response is a redirect, so abort the current request + destroyRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); - // set the extension -> mime - types[extension] = type - } - }) -} + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); + } -/***/ }), + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } -/***/ 3772: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); -module.exports = minimatch -minimatch.Minimatch = Minimatch + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = parseUrl(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); -var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep + // Create the redirected request + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(4691) + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrl.protocol !== currentUrlParts.protocol && + redirectUrl.protocol !== "https:" || + redirectUrl.host !== currentHost && + !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + } -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} + // Evaluate the beforeRedirect callback + if (isFunction(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' + // Perform the redirected request + this._performRequest(); +}; -// * => any number of characters -var star = qmark + '*?' +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters, ensuring that input is an object + if (isURL(input)) { + input = spreadUrlObject(input); + } + else if (isString(input)) { + input = spreadUrlObject(parseUrl(input)); + } + else { + callback = options; + options = validateUrl(input); + input = { protocol: protocol }; + } + if (isFunction(options)) { + callback = options; + options = null; + } -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString(options.host) && !isString(options.hostname)) { + options.hostname = "::1"; + } -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } -// normalizes slashes. -var slashSplit = /\/+/ + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; } -function ext (a, b) { - b = b || {} - var t = {} - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - return t -} +function noop() { /* empty */ } -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch +function parseUrl(input) { + var parsed; + /* istanbul ignore else */ + if (useNativeURL) { + parsed = new URL(input); } - - var orig = minimatch - - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) + else { + // Ensure the URL is valid and absolute + parsed = validateUrl(url.parse(input)); + if (!isString(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } } + return parsed; +} - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - m.Minimatch.defaults = function defaults (options) { - return orig.defaults(ext(def, options)).Minimatch - } +function resolveUrl(relative, base) { + /* istanbul ignore next */ + return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); +} - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) +function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); } - - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); } + return input; +} - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) +function spreadUrlObject(urlObject, target) { + var spread = target || {}; + for (var key of preservedUrlFields) { + spread[key] = urlObject[key]; } - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) + // Fix IPv6 hostname + if (spread.hostname.startsWith("[")) { + spread.hostname = spread.hostname.slice(1, -1); } - - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) + // Ensure port is a number + if (spread.port !== "") { + spread.port = Number(spread.port); } + // Concatenate path + spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - return m -} - -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch + return spread; } -function minimatch (p, pattern, options) { - assertValidPattern(pattern) - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } } - - return new Minimatch(pattern, options).match(p) + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } - - assertValidPattern(pattern) - - if (!options) options = {} - - pattern = pattern.trim() - - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') +function createErrorType(code, message, baseClass) { + // Create constructor + function CustomError(properties) { + Error.captureStackTrace(this, this.constructor); + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; } - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial - - // make the set of regexps etc. - this.make() + // Attach constructor and set default properties + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false, + }, + name: { + value: "Error [" + code + "]", + enumerable: false, + }, + }); + return CustomError; } -Minimatch.prototype.debug = function () {} - -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return +function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); } + request.on("error", noop); + request.destroy(error); +} - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - - if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } - - this.debug(this.pattern, set) +function isSubdomain(subdomain, domain) { + assert(isString(subdomain) && isString(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) +function isString(value) { + return typeof value === "string" || value instanceof String; +} - this.debug(this.pattern, set) +function isFunction(value) { + return typeof value === "function"; +} - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) +function isBuffer(value) { + return typeof value === "object" && ("length" in value); +} - this.debug(this.pattern, set) +function isURL(value) { + return URL && value instanceof URL; +} - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; - this.debug(this.pattern, set) - this.set = set -} +/***/ }), -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 +/***/ 6454: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (options.nonegate) return +var CombinedStream = __nccwpck_require__(5630); +var util = __nccwpck_require__(9023); +var path = __nccwpck_require__(6928); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var parseUrl = (__nccwpck_require__(7016).parse); +var fs = __nccwpck_require__(9896); +var Stream = (__nccwpck_require__(2203).Stream); +var mime = __nccwpck_require__(4096); +var asynckit = __nccwpck_require__(1324); +var populate = __nccwpck_require__(1835); - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } +// Public API +module.exports = FormData; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} +// make it a Stream +util.inherits(FormData, CombinedStream); -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } -Minimatch.prototype.braceExpand = braceExpand + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; } +} - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - assertValidPattern(pattern) +FormData.prototype.append = function(field, value, options) { - // Thanks to Yeting Li for - // improving this regexp to avoid a ReDOS vulnerability. - if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { - // shortcut. no need to expand. - return [pattern] + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; } - return expand(pattern) -} + var append = CombinedStream.prototype.append.bind(this); -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; } - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; } -} -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - assertValidPattern(pattern) + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); - var options = this.options + append(header); + append(value); + append(footer); - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); } - if (pattern === '') return '' - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this + this._valueLength += valueLength; - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; } - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } +FormData.prototype._lengthRetriever = function(value, callback) { - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } + if (value.hasOwnProperty('fd')) { - case '\\': - clearStateChar() - escaping = true - continue + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue + var fileSize; - case '(': - if (inClass) { - re += '(' - continue + if (err) { + callback(err); + return; } - if (!stateChar) { - re += '\\(' - continue - } + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue + // something else + } else { + callback('Unknown stream'); + } +}; - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } - clearStateChar() - re += '|' - continue + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; - if (inClass) { - re += '\\' + c - continue - } + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } + // skip nullish headers. + if (header == null) { + continue; + } - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } - default: - // swallow any state char that wasn't consumed - clearStateChar() + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } +FormData.prototype._getContentDisposition = function(value, options) { - re += c + var filename + , contentDisposition + ; - } // switch - } // for + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] + if (filename) { + contentDisposition = 'filename="' + filename + '"'; } - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } + return contentDisposition; +}; - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) +FormData.prototype._getContentType = function(value, options) { - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + // use custom content-type above all + var contentType = options.contentType; - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); } - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '[': case '.': case '(': addPatternStart = true + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; } - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } - nlLast += nlAfter + return contentType; +}; - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); } - nlAfter = cleanAfter - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe } - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re + return formHeaders; +}; + +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; + +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); } - if (addPatternStart) { - re = patternStart + re + return this._boundary; +}; + +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; + +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); } - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) + this._boundary = boundary; +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) /* istanbul ignore next - should be impossible */ { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); } - regExp._glob = pattern - regExp._src = re + return knownLength; +}; - return regExp -} +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp + return hasKnownLength; +}; - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - if (!set.length) { - this.regexp = false - return this.regexp + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - var options = this.options - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function(length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' + // use custom params + } else { - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } } - return this.regexp -} -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); } - return list -} -Minimatch.prototype.match = function match (f, partial) { - if (typeof partial === 'undefined') partial = this.partial - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } - if (f === '/' && partial) return true + // add content length + if (length) { + request.setHeader('Content-Length', length); + } - var options = this.options + this.pipe(request); + if (cb) { + var onResponse; - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) + return cb.call(this, error, responce); + }; - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. + onResponse = callback.bind(this, null); - var set = this.set - this.debug(this.pattern, 'set', set) + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } + return request; +}; - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); } +}; - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} +FormData.prototype.toString = function () { + return '[object FormData]'; +}; -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +/***/ }), - this.debug('matchOne', file.length, pattern.length) +/***/ 1835: +/***/ ((module) => { - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] +// populates missing values +module.exports = function(dst, src) { - this.debug(pattern, p, f) + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false + return dst; +}; - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } +/***/ }), - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] +/***/ 3813: +/***/ ((module) => { - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) +"use strict"; - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - /* istanbul ignore if */ - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false + +/***/ }), + +/***/ 201: +/***/ ((module) => { + +// https://github.com/electron/electron/issues/2288 +function isElectron() { + // Renderer process + if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') { + return true; + } + + // Main process + if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) { + return true; } - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - hit = f === p - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) + // Detect the user agent when the `nodeIntegration` option is set to false + if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) { + return true; } - if (!hit) return false - } + return false; +} - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* +module.exports = isElectron; - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else /* istanbul ignore else */ if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - return (fi === fl - 1) && (file[fi] === '') - } - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') -} +/***/ }), -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} +/***/ 6543: +/***/ ((module) => { -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} +"use strict"; + + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; + +module.exports = isStream; /***/ }), -/***/ 744: -/***/ ((module) => { +/***/ 9829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Helpers. +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Module exports. */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +module.exports = __nccwpck_require__(1813) -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private + +/***/ }), + +/***/ 4096: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} + /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Module dependencies. + * @private */ -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} +var db = __nccwpck_require__(9829) +var extname = (__nccwpck_require__(6928).extname) /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Module variables. + * @private */ -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i /** - * Pluralization helper. + * Module exports. + * @public */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) -/***/ }), +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -/***/ 2766: -/***/ ((module) => { +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } -"use strict"; + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); + if (mime && mime.charset) { + return mime.charset + } - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + return false +} -/***/ }), +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ -/***/ 6459: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } -"use strict"; + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str -Object.defineProperty(exports, "__esModule", ({ value: true })); -const EventEmitter = __nccwpck_require__(301); -const p_timeout_1 = __nccwpck_require__(4802); -const priority_queue_1 = __nccwpck_require__(5905); -// eslint-disable-next-line @typescript-eslint/no-empty-function -const empty = () => { }; -const timeoutError = new p_timeout_1.TimeoutError(); -/** -Promise queue with concurrency control. -*/ -class PQueue extends EventEmitter { - constructor(options) { - var _a, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; - } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; - } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit('next'); - } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit('idle'); - } - } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = undefined; - } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === undefined) { - const delay = this._intervalEnd - now; - if (delay < 0) { - // Act as the interval was done - // We don't need to resume it here because it will be resumed on line 160 - this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; - } - else { - // Act as the interval is pending - if (this._timeoutId === undefined) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - // We can clear the interval ("pause") - // Because we can redo it later ("resume") - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = undefined; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit('active'); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; - } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== undefined) { - return; - } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; - } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - // eslint-disable-next-line no-empty - while (this._tryToStartAnother()) { } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { - if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return undefined; - }); - resolve(await operation); - } - catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit('add'); - }); - } - /** - Same as `.add()`, but accepts an array of sync or async functions. + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; - } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); - } - /** - Can be called multiple times. Useful if you for example add additional items at a later time. + return mime +} - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - // Instantly resolve if the queue is empty - if (this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return } - /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - // Instantly resolve if none pending and if nothing else is queued - if (this._pendingCount === 0 && this._queue.size === 0) { - return; + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue } - return new Promise(resolve => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. + } - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - return this._queue.filter(options).length; - } - /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; - } - /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; - } - /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; + // set the extension -> mime + types[extension] = type } + }) +} + + +/***/ }), + +/***/ 3772: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __nccwpck_require__(4691) + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t } -exports["default"] = PQueue; +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } -/***/ }), + var orig = minimatch -/***/ 9015: -/***/ ((__unused_webpack_module, exports) => { + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } -"use strict"; + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound -// Used to compute insertion index to keep queue sorted after insertion -function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = (count / 2) | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count -= step + 1; - } - else { - count = step; - } - } - return first; -} -exports["default"] = lowerBound; + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } -/***/ }), + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } -/***/ 5905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } -"use strict"; + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lower_bound_1 = __nccwpck_require__(9015); -class PriorityQueue { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; - } - const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); - this._queue.splice(index, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } + return m } -exports["default"] = PriorityQueue; +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch +} -/***/ }), +function minimatch (p, pattern, options) { + assertValidPattern(pattern) -/***/ 301: -/***/ ((module) => { + if (!options) options = {} -"use strict"; + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + return new Minimatch(pattern, options).match(p) +} -var has = Object.prototype.hasOwnProperty - , prefix = '~'; +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} + assertValidPattern(pattern) -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); + if (!options) options = {} - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} + pattern = pattern.trim() -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() } -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return } - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; + // step 1: figure out negation, etc. + this.parseNegate() - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; + // step 2: expand braces + var set = this.globSet = this.braceExpand() - return emitter; -} + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} + this.debug(this.pattern, set) -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set } -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 - if (this._eventsCount === 0) return names; + if (options.nonegate) return - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} - return names; -}; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; +Minimatch.prototype.braceExpand = braceExpand - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] } - return ee; -}; + return expand(pattern) +} -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) - if (!this._events[evt]) return false; + var options = this.options - var listeners = this._events[evt] - , len = arguments.length - , args - , i; + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } + } - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } + if (!stateChar) { + re += '\\(' + continue + } - listeners[i].fn.apply(listeners[i].context, args); - } - } - } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue - return true; -}; + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; + clearStateChar() + re += '|' + continue - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() - var listeners = this._events[evt]; + if (inClass) { + re += '\\' + c + continue + } - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } + inClass = true + classStart = i + reClassStart = re.length + re += c + continue - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } - return this; -}; + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; + // finish up the class. + hasMagic = true + inClass = false + re += c + continue - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } + default: + // swallow any state char that wasn't consumed + clearStateChar() - return this; -}; + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; + re += c -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; + } // switch + } // for -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; -} + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) -/***/ }), + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type -/***/ 2103: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -"use strict"; + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } -const retry = __nccwpck_require__(5546); + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true + } -const networkErrorMsgs = [ - 'Failed to fetch', // Chrome - 'NetworkError when attempting to fetch resource.', // Firefox - 'The Internet connection appears to be offline.', // Safari - 'Network request failed' // `cross-fetch` -]; + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] -class AbortError extends Error { - constructor(message) { - super(); + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) - if (message instanceof Error) { - this.originalError = message; - ({message} = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } + nlLast += nlAfter - this.name = 'AbortError'; - this.message = message; - } -} + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter -const decorateErrorWithCounts = (error, attemptNumber, options) => { - // Minus 1 from attemptNumber because the first attempt does not count as a retry - const retriesLeft = options.retries - (attemptNumber - 1); + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; -}; + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } -const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); + if (addPatternStart) { + re = patternStart + re + } -const pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => {}, - retries: 10, - ...options - }; + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } - const operation = retry.operation(options); + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } - operation.attempt(async attemptNumber => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); + regExp._glob = pattern + regExp._src = re - try { - await options.onFailedAttempt(error); - } catch (error) { - reject(error); - return; - } + return regExp +} - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); -}); +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} -module.exports = pRetry; -// TODO: remove this in the next major version -module.exports["default"] = pRetry; +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp -module.exports.AbortError = AbortError; + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options -/***/ }), + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' -/***/ 4802: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') -"use strict"; + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' -const pFinally = __nccwpck_require__(2766); + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp +} -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list } -const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== 'number' || milliseconds < 0) { - throw new TypeError('Expected `milliseconds` to be a positive number'); - } +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' - if (milliseconds === Infinity) { - resolve(promise); - return; - } + if (f === '/' && partial) return true - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } + var options = this.options - return; - } + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - if (typeof promise.cancel === 'function') { - promise.cancel(); - } + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - reject(timeoutError); - }, milliseconds); + var set = this.set + this.debug(this.pattern, 'set', set) - // TODO: Use native `finally` keyword when targeting Node.js 10 - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } -module.exports = pTimeout; -// TODO: Remove this for the next major release -module.exports["default"] = pTimeout; + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } -module.exports.TimeoutError = TimeoutError; + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options -/***/ }), + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) -/***/ 7777: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.debug('matchOne', file.length, pattern.length) -"use strict"; + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + this.debug(pattern, p, f) -var parseUrl = (__nccwpck_require__(7016).parse); + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false -var DEFAULT_PORTS = { - ftp: 21, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443, -}; + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) -var stringEndsWith = String.prototype.endsWith || function(s) { - return s.length <= this.length && - this.indexOf(s, this.length - s.length) !== -1; -}; + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } -/** - * @param {string|object} url - The URL, or the result from url.parse. - * @return {string} The URL of the proxy that should handle the request to the - * given URL. If no proxy is set, this will be an empty string. - */ -function getProxyForUrl(url) { - var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; - var proto = parsedUrl.protocol; - var hostname = parsedUrl.host; - var port = parsedUrl.port; - if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { - return ''; // Don't proxy URLs without a valid scheme or host. - } + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] - proto = proto.split(':', 1)[0]; - // Stripping ports in this way instead of using parsedUrl.hostname to make - // sure that the brackets around IPv6 addresses are kept. - hostname = hostname.replace(/:\d*$/, ''); - port = parseInt(port) || DEFAULT_PORTS[proto] || 0; - if (!shouldProxy(hostname, port)) { - return ''; // Don't proxy URLs that match NO_PROXY. - } + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - var proxy = - getEnv('npm_config_' + proto + '_proxy') || - getEnv(proto + '_proxy') || - getEnv('npm_config_proxy') || - getEnv('all_proxy'); - if (proxy && proxy.indexOf('://') === -1) { - // Missing scheme in proxy, default to the requested URL's scheme. - proxy = proto + '://' + proxy; - } - return proxy; -} + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } -/** - * Determines whether a given URL should be proxied. - * - * @param {string} hostname - The host name of the URL. - * @param {number} port - The effective port of the URL. - * @returns {boolean} Whether the given URL should be proxied. - * @private - */ -function shouldProxy(hostname, port) { - var NO_PROXY = - (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); - if (!NO_PROXY) { - return true; // Always proxy if NO_PROXY is not set. - } - if (NO_PROXY === '*') { - return false; // Never proxy if wildcard is set. - } + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } - return NO_PROXY.split(/[,\s]/).every(function(proxy) { - if (!proxy) { - return true; // Skip zero-length hosts. - } - var parsedProxy = proxy.match(/^(.+):(\d+)$/); - var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; - var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; - if (parsedProxyPort && parsedProxyPort !== port) { - return true; // Skip if ports don't match. + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false } - if (!/^[.*]/.test(parsedProxyHostname)) { - // No wildcards, so stop proxying if there is an exact match. - return hostname !== parsedProxyHostname; + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) } - if (parsedProxyHostname.charAt(0) === '*') { - // Remove leading wildcard. - parsedProxyHostname = parsedProxyHostname.slice(1); - } - // Stop proxying if the hostname ends with the no_proxy host. - return !stringEndsWith.call(hostname, parsedProxyHostname); - }); + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') } -/** - * Get the value for an environment variable. - * - * @param {string} key - The name of the environment variable. - * @return {string} The value of the environment variable. - * @private - */ -function getEnv(key) { - return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') } -exports.getProxyForUrl = getProxyForUrl; +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} /***/ }), -/***/ 5546: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(7084); - -/***/ }), +/***/ 744: +/***/ ((module) => { -/***/ 7084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Helpers. + */ -var RetryOperation = __nccwpck_require__(9538); +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); +function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; } - - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; } +} - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); - - return timeouts; -}; - -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; - - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - - return timeout; -}; +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; } - - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; } + return ms + 'ms'; +} - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); +/** + * Pluralization helper. + */ - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} /***/ }), -/***/ 9538: +/***/ 2766: /***/ ((module) => { -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } - - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; - - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; - -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); -} +"use strict"; -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); - this._timeouts = []; - this._cachedTimeouts = null; + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); }; -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; - } +/***/ }), - this._errors.push(err); +/***/ 6459: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const EventEmitter = __nccwpck_require__(301); +const p_timeout_1 = __nccwpck_require__(4802); +const priority_queue_1 = __nccwpck_require__(5905); +// eslint-disable-next-line @typescript-eslint/no-empty-function +const empty = () => { }; +const timeoutError = new p_timeout_1.TimeoutError(); +/** +Promise queue with concurrency control. +*/ +class PQueue extends EventEmitter { + constructor(options) { + var _a, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); + } + if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit('next'); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit('idle'); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = undefined; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === undefined) { + const delay = this._intervalEnd - now; + if (delay < 0) { + // Act as the interval was done + // We don't need to resume it here because it will be resumed on line 160 + this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; + } + else { + // Act as the interval is pending + if (this._timeoutId === undefined) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + // We can clear the interval ("pause") + // Because we can redo it later ("resume") + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = undefined; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit('active'); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== undefined) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = undefined; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + // eslint-disable-next-line no-empty + while (this._tryToStartAnother()) { } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { + if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return undefined; + }); + resolve(await operation); + } + catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit('add'); + }); } - } - - var self = this; - this._timer = setTimeout(function() { - self._attempts++; - - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); + /** + Same as `.add()`, but accepts an array of sync or async functions. - if (self._options.unref) { - self._timeout.unref(); - } + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); } - - self._fn(self._attempts); - }, timeout); - - if (this._options.unref) { - this._timer.unref(); - } - - return true; -}; - -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; } - } - - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } - - this._operationStart = new Date().getTime(); - - this._fn(this._attempts); -}; - -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = RetryOperation.prototype.try; - -RetryOperation.prototype.errors = function() { - return this._errors; -}; - -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; - -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - - counts[message] = count; - - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); } - } - - return mainError; -}; - - -/***/ }), - -/***/ 1450: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const os = __nccwpck_require__(857); -const tty = __nccwpck_require__(2018); -const hasFlag = __nccwpck_require__(3813); - -const {env} = process; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} + /** + Can be called multiple times. Useful if you for example add additional items at a later time. -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } -} + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + // Instantly resolve if the queue is empty + if (this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. -function translateLevel(level) { - if (level === 0) { - return false; - } + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + // Instantly resolve if none pending and if nothing else is queued + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } } +exports["default"] = PQueue; -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } +/***/ }), - const min = forceColor || 0; +/***/ 9015: +/***/ ((__unused_webpack_module, exports) => { - if (env.TERM === 'dumb') { - return min; - } +"use strict"; - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound +// Used to compute insertion index to keep queue sorted after insertion +function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = (count / 2) | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; + } + else { + count = step; + } + } + return first; +} +exports["default"] = lowerBound; - return 1; - } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } +/***/ }), - return min; - } +/***/ 5905: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +"use strict"; - if (env.COLORTERM === 'truecolor') { - return 3; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lower_bound_1 = __nccwpck_require__(9015); +class PriorityQueue { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } +} +exports["default"] = PriorityQueue; - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } +/***/ }), - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +/***/ 301: +/***/ ((module) => { - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } +"use strict"; - if ('COLORTERM' in env) { - return 1; - } - return min; -} +var has = Object.prototype.hasOwnProperty + , prefix = '~'; -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); -} +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} -/***/ }), +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} -/***/ 770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } -module.exports = __nccwpck_require__(218); + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; -/***/ }), + return emitter; +} -/***/ 218: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} -"use strict"; +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; -var net = __nccwpck_require__(9278); -var tls = __nccwpck_require__(4756); -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var events = __nccwpck_require__(4434); -var assert = __nccwpck_require__(2613); -var util = __nccwpck_require__(9023); + if (this._eventsCount === 0) return names; + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + return names; +}; -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} + return ee; +}; +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + if (!this._events[evt]) return false; - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - function onFree() { - self.emit('free', socket, options); + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; } - }); -}; -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); } - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); + return true; +}; - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; } - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); + var listeners = this._events[evt]; - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - - function onError(cause) { - connectReq.removeAllListeners(); - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); } + + return this; }; -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; } + + return this; }; -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; } -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} +/***/ }), -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); - } -} else { - debug = function() {}; -} -exports.debug = debug; // for test +/***/ 2103: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -/***/ }), +const retry = __nccwpck_require__(5546); -/***/ 2048: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const networkErrorMsgs = [ + 'Failed to fetch', // Chrome + 'NetworkError when attempting to fetch resource.', // Firefox + 'The Internet connection appears to be offline.', // Safari + 'Network request failed' // `cross-fetch` +]; -"use strict"; +class AbortError extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({message} = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "NIL", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "stringify", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); + this.name = 'AbortError'; + this.message = message; + } +} + +const decorateErrorWithCounts = (error, attemptNumber, options) => { + // Minus 1 from attemptNumber because the first attempt does not count as a retry + const retriesLeft = options.retries - (attemptNumber - 1); + + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; +}; -var _v = _interopRequireDefault(__nccwpck_require__(6415)); +const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); -var _v2 = _interopRequireDefault(__nccwpck_require__(1697)); +const pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => {}, + retries: 10, + ...options + }; -var _v3 = _interopRequireDefault(__nccwpck_require__(4676)); + const operation = retry.operation(options); -var _v4 = _interopRequireDefault(__nccwpck_require__(9771)); + operation.attempt(async attemptNumber => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } -var _nil = _interopRequireDefault(__nccwpck_require__(7723)); + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); -var _version = _interopRequireDefault(__nccwpck_require__(5868)); + try { + await options.onFailedAttempt(error); + } catch (error) { + reject(error); + return; + } -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); +}); -var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); +module.exports = pRetry; +// TODO: remove this in the next major version +module.exports["default"] = pRetry; -var _parse = _interopRequireDefault(__nccwpck_require__(7267)); +module.exports.AbortError = AbortError; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 216: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4802: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +const pFinally = __nccwpck_require__(2766); -var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); +class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== 'number' || milliseconds < 0) { + throw new TypeError('Expected `milliseconds` to be a positive number'); + } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } + if (milliseconds === Infinity) { + resolve(promise); + return; + } - return _crypto.default.createHash('md5').update(bytes).digest(); -} + const timer = setTimeout(() => { + if (typeof fallback === 'function') { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } + + return; + } -var _default = md5; -exports["default"] = _default; + const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + + if (typeof promise.cancel === 'function') { + promise.cancel(); + } -/***/ }), + reject(timeoutError); + }, milliseconds); -/***/ 7723: -/***/ ((__unused_webpack_module, exports) => { + // TODO: Use native `finally` keyword when targeting Node.js 10 + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); +}); -"use strict"; +module.exports = pTimeout; +// TODO: Remove this for the next major release +module.exports["default"] = pTimeout; +module.exports.TimeoutError = TimeoutError; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; /***/ }), -/***/ 7267: +/***/ 7777: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +var parseUrl = (__nccwpck_require__(7016).parse); -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); +var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && + this.indexOf(s, this.length - s.length) !== -1; +}; -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); +/** + * @param {string|object} url - The URL, or the result from url.parse. + * @return {string} The URL of the proxy that should handle the request to the + * given URL. If no proxy is set, this will be an empty string. + */ +function getProxyForUrl(url) { + var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { + return ''; // Don't proxy URLs without a valid scheme or host. } - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + proto = proto.split(':', 1)[0]; + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, ''); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ''; // Don't proxy URLs that match NO_PROXY. + } - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ + var proxy = + getEnv('npm_config_' + proto + '_proxy') || + getEnv(proto + '_proxy') || + getEnv('npm_config_proxy') || + getEnv('all_proxy'); + if (proxy && proxy.indexOf('://') === -1) { + // Missing scheme in proxy, default to the requested URL's scheme. + proxy = proto + '://' + proxy; + } + return proxy; +} - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ +/** + * Determines whether a given URL should be proxied. + * + * @param {string} hostname - The host name of the URL. + * @param {number} port - The effective port of the URL. + * @returns {boolean} Whether the given URL should be proxied. + * @private + */ +function shouldProxy(hostname, port) { + var NO_PROXY = + (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); + if (!NO_PROXY) { + return true; // Always proxy if NO_PROXY is not set. + } + if (NO_PROXY === '*') { + return false; // Never proxy if wildcard is set. + } - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; // Skip zero-length hosts. + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; // Skip if ports don't match. + } - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + if (!/^[.*]/.test(parsedProxyHostname)) { + // No wildcards, so stop proxying if there is an exact match. + return hostname !== parsedProxyHostname; + } - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; + if (parsedProxyHostname.charAt(0) === '*') { + // Remove leading wildcard. + parsedProxyHostname = parsedProxyHostname.slice(1); + } + // Stop proxying if the hostname ends with the no_proxy host. + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); } -var _default = parse; -exports["default"] = _default; +/** + * Get the value for an environment variable. + * + * @param {string} key - The name of the environment variable. + * @return {string} The value of the environment variable. + * @private + */ +function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; +} -/***/ }), +exports.getProxyForUrl = getProxyForUrl; -/***/ 7879: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; +/***/ }), +/***/ 5546: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports["default"] = _default; +module.exports = __nccwpck_require__(7084); /***/ }), -/***/ 2973: +/***/ 7084: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate +var RetryOperation = __nccwpck_require__(9538); -let poolPtr = rnds8Pool.length; +exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); +}; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); +exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } - poolPtr = 0; + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } -/***/ }), + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } -/***/ 507: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } -"use strict"; + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); + return timeouts; +}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; -var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return timeout; +}; -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; } - return _crypto.default.createHash('sha1').update(bytes).digest(); -} - -var _default = sha1; -exports["default"] = _default; - -/***/ }), + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); + } + } + } -/***/ 7597: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; -"use strict"; + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; +/***/ 9538: +/***/ ((module) => { -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); -} +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; + } -function stringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); } +} +module.exports = RetryOperation; - return uuid; +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); } -var _default = stringify; -exports["default"] = _default; - -/***/ }), - -/***/ 6415: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } -"use strict"; + this._timeouts = []; + this._cachedTimeouts = null; +}; +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (!err) { + return false; + } + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; + } -var _rng = _interopRequireDefault(__nccwpck_require__(2973)); + this._errors.push(err); -var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var self = this; + this._timer = setTimeout(function() { + self._attempts++; -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); -let _clockseq; // Previous uuid creation time + if (self._options.unref) { + self._timeout.unref(); + } + } + self._fn(self._attempts); + }, timeout); -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + if (this._options.unref) { + this._timer.unref(); + } -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 + return true; +}; - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + } + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock + this._operationStart = new Date().getTime(); - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + this._fn(this._attempts); +}; - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; +RetryOperation.prototype.start = RetryOperation.prototype.try; - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested +RetryOperation.prototype.errors = function() { + return this._errors; +}; +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + var counts = {}; + var mainError = null; + var mainErrorCount = 0; - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; - b[i++] = clockseq & 0xff; // `node` + counts[message] = count; - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } } - return buf || (0, _stringify.default)(b); -} + return mainError; +}; -var _default = v1; -exports["default"] = _default; /***/ }), -/***/ 1697: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1450: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const os = __nccwpck_require__(857); +const tty = __nccwpck_require__(2018); +const hasFlag = __nccwpck_require__(3813); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _v = _interopRequireDefault(__nccwpck_require__(2930)); +const {env} = process; -var _md = _interopRequireDefault(__nccwpck_require__(216)); +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports["default"] = _default; +function translateLevel(level) { + if (level === 0) { + return false; + } -/***/ }), + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} -/***/ 2930: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } -"use strict"; + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + if (hasFlag('color=256')) { + return 2; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = _default; -exports.URL = exports.DNS = void 0; + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } -var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); + const min = forceColor || 0; -var _parse = _interopRequireDefault(__nccwpck_require__(7267)); + if (env.TERM === 'dumb') { + return min; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape + return 1; + } - const bytes = []; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } + return min; + } - return bytes; -} + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; + if (env.COLORTERM === 'truecolor') { + return 3; + } -function _default(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; + if ('COLORTERM' in env) { + return 1; + } - if (buf) { - offset = offset || 0; + return min; +} - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} - return buf; - } +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; - return (0, _stringify.default)(bytes); - } // Function#name is not settable on some platforms (#270) +/***/ }), - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support +/***/ 770: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = __nccwpck_require__(218); - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} /***/ }), -/***/ 4676: +/***/ 218: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _rng = _interopRequireDefault(__nccwpck_require__(2973)); +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); -var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; -function v4(options, buf, offset) { - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} - if (buf) { - offset = offset || 0; +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; - return (0, _stringify.default)(rnds); + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } + } + socket.destroy(); + self.removeSocket(socket); + }); } +util.inherits(TunnelingAgent, events.EventEmitter); -var _default = v4; -exports["default"] = _default; +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); -/***/ }), + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } -/***/ 9771: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); -"use strict"; + function onFree() { + self.emit('free', socket, options); + } + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); -var _v = _interopRequireDefault(__nccwpck_require__(2930)); + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } -var _sha = _interopRequireDefault(__nccwpck_require__(507)); + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports["default"] = _default; + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } -/***/ }), + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); -/***/ 6200: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } -"use strict"; + function onError(cause) { + connectReq.removeAllListeners(); + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); -var _regex = _interopRequireDefault(__nccwpck_require__(7879)); + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); } -var _default = validate; -exports["default"] = _default; - -/***/ }), - -/***/ 5868: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); } - - return parseInt(uuid.substr(14, 1), 16); +} else { + debug = function() {}; } +exports.debug = debug; // for test -var _default = version; -exports["default"] = _default; /***/ }), @@ -13638,6 +14343,14 @@ module.exports = require("assert"); /***/ }), +/***/ 5317: +/***/ ((module) => { + +"use strict"; +module.exports = require("child_process"); + +/***/ }), + /***/ 6982: /***/ ((module) => { @@ -13766,6 +14479,22 @@ module.exports = require("stream"); /***/ }), +/***/ 3193: +/***/ ((module) => { + +"use strict"; +module.exports = require("string_decoder"); + +/***/ }), + +/***/ 3557: +/***/ ((module) => { + +"use strict"; +module.exports = require("timers"); + +/***/ }), + /***/ 4756: /***/ ((module) => {