From 7ee65a14f1236e0b53717df1668b188013c299e5 Mon Sep 17 00:00:00 2001 From: Paul B Date: Mon, 23 May 2022 16:35:29 +0200 Subject: [PATCH] 1.1.3 --- dist/index.js | 104608 +++++++++++++++++----------------- dist/index.js.map | 2 +- dist/licenses.txt | 447 +- dist/sourcemap-register.js | 2 +- package-lock.json | 4 +- package.json | 2 +- 6 files changed, 53853 insertions(+), 51212 deletions(-) diff --git a/dist/index.js b/dist/index.js index 4520fb48..3ef428b0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -625,6 +625,16 @@ function getIDToken(aud) { }); } exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(81327); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(81327); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); //# sourceMappingURL=core.js.map /***/ }), @@ -694,8 +704,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(39925); -const auth_1 = __nccwpck_require__(23702); +const http_client_1 = __nccwpck_require__(96255); +const auth_1 = __nccwpck_require__(35526); const core_1 = __nccwpck_require__(42186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { @@ -762,6 +772,296 @@ exports.OidcClient = OidcClient; /***/ }), +/***/ 81327: +/***/ (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.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(57147); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map + +/***/ }), + /***/ 5278: /***/ ((__unused_webpack_module, exports) => { @@ -1674,7 +1974,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(39925)); +const httpClient = __importStar(__nccwpck_require__(96255)); function getAuthString(token, options) { if (!token && !options.auth) { throw new Error('Parameter token or opts.auth is required'); @@ -1759,28 +2059,41 @@ exports.getOctokitOptions = getOctokitOptions; /***/ }), -/***/ 23702: -/***/ ((__unused_webpack_module, exports) => { +/***/ 35526: +/***/ (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) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } // This handler cannot handle 401 - canHandleAuthentication(response) { + canHandleAuthentication() { return false; } - handleAuthentication(httpClient, requestInfo, objs) { - return null; + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } } exports.BasicCredentialHandler = BasicCredentialHandler; @@ -1791,14 +2104,19 @@ class BearerCredentialHandler { // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { - options.headers['Authorization'] = 'Bearer ' + this.token; + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; } // This handler cannot handle 401 - canHandleAuthentication(response) { + canHandleAuthentication() { return false; } - handleAuthentication(httpClient, requestInfo, objs) { - return null; + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } } exports.BearerCredentialHandler = BearerCredentialHandler; @@ -1809,32 +2127,66 @@ class PersonalAccessTokenCredentialHandler { // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } // This handler cannot handle 401 - canHandleAuthentication(response) { + canHandleAuthentication() { return false; } - handleAuthentication(httpClient, requestInfo, objs) { - return null; + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } } exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; - +//# sourceMappingURL=auth.js.map /***/ }), -/***/ 39925: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 96255: +/***/ (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]; } }); +}) : (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 })); -const http = __nccwpck_require__(13685); -const https = __nccwpck_require__(95687); -const pm = __nccwpck_require__(16443); -let tunnel; +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(13685)); +const https = __importStar(__nccwpck_require__(95687)); +const pm = __importStar(__nccwpck_require__(19835)); +const tunnel = __importStar(__nccwpck_require__(74294)); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -1879,7 +2231,7 @@ var MediaTypes; * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; @@ -1912,20 +2264,22 @@ class HttpClientResponse { this.message = message; } readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); + 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) { - let parsedUrl = new URL(requestUrl); + const parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; @@ -1968,141 +2322,169 @@ class HttpClient { } } options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); } patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); } put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); } head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); } sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(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 */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let 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); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let 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); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let 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); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); + 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); + }); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; + 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; } } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); + 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--; } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying return response; } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let 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. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; + } while (numTries < maxTries); + return response; + }); } /** * Needs to be called if keepAlive is set to true in request options. @@ -2119,14 +2501,22 @@ class HttpClient { * @param data */ requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); + 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); + } } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); + this.requestRawWithCallback(info, data, callbackForResult); + }); }); } /** @@ -2136,21 +2526,24 @@ class HttpClient { * @param onResult */ requestRawWithCallback(info, data, onResult) { - let socket; if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; - let handleResult = (err, res) => { + function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, 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; }); @@ -2159,12 +2552,12 @@ class HttpClient { if (socket) { socket.end(); } - handleResult(new Error('Request timeout: ' + info.options.path), null); + handleResult(new Error(`Request timeout: ${info.options.path}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers - handleResult(err, null); + handleResult(err); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); @@ -2185,7 +2578,7 @@ class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); + const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { @@ -2209,21 +2602,19 @@ class HttpClient { info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { - this.handlers.forEach(handler => { + for (const handler of this.handlers) { handler.prepareRequest(info.options); - }); + } } return info; } _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; @@ -2232,8 +2623,8 @@ class HttpClient { } _getAgent(parsedUrl) { let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } @@ -2241,29 +2632,22 @@ class HttpClient { agent = this._agent; } // if agent is already assigned use that agent. - if (!!agent) { + if (agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; - if (!!this.requestOptions) { + if (this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __nccwpck_require__(74294); - } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { const agentOptions = { - maxSockets: maxSockets, + maxSockets, keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } + 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:'; @@ -2278,7 +2662,7 @@ class HttpClient { } // 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: maxSockets }; + const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } @@ -2297,109 +2681,117 @@ class HttpClient { return agent; } _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; + 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)); + }); } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); + _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; + } } - else { - obj = JSON.parse(contents); + 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.result = obj; + response.headers = res.message.headers; } - 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; + catch (err) { + // Invalid resource (contents not json); leaving result obj null } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; + // 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 { - msg = 'Failed request: (' + statusCode + ')'; + resolve(response); } - let 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 /***/ }), -/***/ 16443: +/***/ 19835: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkBypass = exports.getProxyUrl = void 0; function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; + const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { - return proxyUrl; + return undefined; } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; + 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 { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); + return undefined; } - return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } @@ -2415,12 +2807,12 @@ function checkBypass(reqUrl) { reqPort = 443; } // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy - for (let upperNoProxyItem of noProxy + for (const upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { @@ -2431,7 +2823,7 @@ function checkBypass(reqUrl) { return false; } exports.checkBypass = checkBypass; - +//# sourceMappingURL=proxy.js.map /***/ }), @@ -6147,6 +6539,7 @@ module.exports = { '2.1.0': __nccwpck_require__(8369), '2.2.0': __nccwpck_require__(9320), '2.3.0': __nccwpck_require__(83738), + '2.4.0': __nccwpck_require__(45771), }; @@ -6761,7 +7154,7 @@ class Command { return this._version(); } try { - const { cli } = __nccwpck_require__(81982); + const { cli } = __nccwpck_require__(90841); const chalk = __nccwpck_require__(38707); // eslint-disable-line node/no-extraneous-require cli.action.stop(chalk.bold.red('!')); } @@ -7991,10498 +8384,11757 @@ exports.uniq = uniq; /***/ }), -/***/ 75383: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 40877: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.config = void 0; -const settings_1 = __nccwpck_require__(86464); -const logger_1 = __nccwpck_require__(69599); -function displayWarnings() { - if (process.listenerCount('warning') > 1) - return; - process.on('warning', (warning) => { - console.error(warning.stack); - if (warning.detail) - console.error(warning.detail); - }); +module.exports = async () => { + try { + const {ux} = __nccwpck_require__(90841) + await ux.flush() + } catch (error) { } } -exports.config = { - errorLogger: undefined, - get debug() { - return Boolean(settings_1.settings.debug); - }, - set debug(enabled) { - settings_1.settings.debug = enabled; - if (enabled) - displayWarnings(); - }, - get errlog() { - return settings_1.settings.errlog; - }, - set errlog(errlog) { - if (errlog) { - this.errorLogger = new logger_1.Logger(errlog); - settings_1.settings.errlog = errlog; - } - else { - delete this.errorLogger; - delete settings_1.settings.errlog; - } - }, -}; /***/ }), -/***/ 68463: +/***/ 38174: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CLIError = exports.addOclifExitCode = void 0; -const chalk = __nccwpck_require__(1854); -const indent = __nccwpck_require__(98043); -const cs = __nccwpck_require__(27972); -const wrap = __nccwpck_require__(59824); -const screen = __nccwpck_require__(12051); -const config_1 = __nccwpck_require__(75383); -/** - * properties specific to internal oclif error handling - */ -function addOclifExitCode(error, options) { - if (!('oclif' in error)) { - error.oclif = {}; +exports.ActionBase = void 0; +const util_1 = __nccwpck_require__(73837); +const util_2 = __nccwpck_require__(40765); +class ActionBase { + constructor() { + this.std = 'stderr'; + this.stdmockOrigs = { + stdout: process.stdout.write, + stderr: process.stderr.write, + }; } - error.oclif.exit = (options === null || options === void 0 ? void 0 : options.exit) === undefined ? 2 : options.exit; - return error; -} -exports.addOclifExitCode = addOclifExitCode; -class CLIError extends Error { - constructor(error, options = {}) { - super(error instanceof Error ? error.message : error); - this.oclif = {}; - addOclifExitCode(this, options); - this.code = options.code; + start(action, status, opts = {}) { + this.std = opts.stdout ? 'stdout' : 'stderr'; + const task = { action, status, active: Boolean(this.task && this.task.active) }; + this.task = task; + this._start(); + task.active = true; + this._stdout(true); } - get stack() { - return cs(super.stack, { pretty: true }); + stop(msg = 'done') { + const task = this.task; + if (!task) { + return; + } + this._stop(msg); + task.active = false; + this.task = undefined; + this._stdout(false); } - /** - * @deprecated `render` Errors display should be handled by display function, like pretty-print - * @return {string} returns a string representing the dispay of the error - */ - render() { - if (config_1.config.debug) { - return this.stack; + get globals() { + global['cli-ux'] = global['cli-ux'] || {}; + const globals = global['cli-ux']; + globals.action = globals.action || {}; + return globals; + } + get task() { + return this.globals.action.task; + } + set task(task) { + this.globals.action.task = task; + } + get output() { + return this.globals.output; + } + set output(output) { + this.globals.output = output; + } + get running() { + return Boolean(this.task); + } + get status() { + return this.task ? this.task.status : undefined; + } + set status(status) { + const task = this.task; + if (!task) { + return; } - let output = `${this.name}: ${this.message}`; - output = wrap(output, screen.errtermwidth - 6, { trim: false, hard: true }); - output = indent(output, 3); - output = indent(output, 1, { indent: this.bang, includeEmptyLines: true }); - output = indent(output, 1); - return output; + if (task.status === status) { + return; + } + this._updateStatus(status, task.status); + task.status = status; } - get bang() { - try { - return chalk.red(process.platform === 'win32' ? '»' : '›'); + async pauseAsync(fn, icon) { + const task = this.task; + const active = task && task.active; + if (task && active) { + this._pause(icon); + this._stdout(false); + task.active = false; } - catch { } + const ret = await fn(); + if (task && active) { + this._resume(); + } + return ret; } -} -exports.CLIError = CLIError; -(function (CLIError) { - class Warn extends CLIError { - constructor(err) { - super(err instanceof Error ? err.message : err); - this.name = 'Warning'; + pause(fn, icon) { + const task = this.task; + const active = task && task.active; + if (task && active) { + this._pause(icon); + this._stdout(false); + task.active = false; } - get bang() { - try { - return chalk.yellow(process.platform === 'win32' ? '»' : '›'); + const ret = fn(); + if (task && active) { + this._resume(); + } + return ret; + } + _start() { + throw new Error('not implemented'); + } + _stop(_) { + throw new Error('not implemented'); + } + _resume() { + if (this.task) + this.start(this.task.action, this.task.status); + } + _pause(_) { + throw new Error('not implemented'); + } + _updateStatus(_, __) { } + // mock out stdout/stderr so it doesn't screw up the rendering + _stdout(toggle) { + try { + const outputs = ['stdout', 'stderr']; + if (toggle) { + if (this.stdmocks) + return; + this.stdmockOrigs = { + stdout: process.stdout.write, + stderr: process.stderr.write, + }; + this.stdmocks = []; + for (const std of outputs) { + process[std].write = (...args) => { + this.stdmocks.push([std, args]); + }; + } + } + else { + if (!this.stdmocks) + return; + // this._write('stderr', '\nresetstdmock\n\n\n') + delete this.stdmocks; + for (const std of outputs) + process[std].write = this.stdmockOrigs[std]; } - catch { } + } + catch (error) { + this._write('stderr', (0, util_1.inspect)(error)); } } - CLIError.Warn = Warn; -})(CLIError = exports.CLIError || (exports.CLIError = {})); + // flush mocked stdout/stderr + _flushStdout() { + try { + let output = ''; + let std; + while (this.stdmocks && this.stdmocks.length > 0) { + const cur = this.stdmocks.shift(); + std = cur[0]; + this._write(std, cur[1]); + output += cur[1][0].toString('utf8'); + } + // add newline if there isn't one already + // otherwise we'll just overwrite it when we render + if (output && std && output[output.length - 1] !== '\n') { + this._write(std, '\n'); + } + } + catch (error) { + this._write('stderr', (0, util_1.inspect)(error)); + } + } + // write to the real stdout/stderr + _write(std, s) { + this.stdmockOrigs[std].apply(process[std], (0, util_2.castArray)(s)); + } +} +exports.ActionBase = ActionBase; /***/ }), -/***/ 30950: +/***/ 9749: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var __webpack_unused_export__; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ExitError = void 0; -const cli_1 = __nccwpck_require__(68463); -class ExitError extends cli_1.CLIError { - constructor(exitCode = 1) { - super(`EEXIT: ${exitCode}`, { exit: exitCode }); - this.code = 'EEXIT'; - } - render() { - return ''; +// tslint:disable restrict-plus-operands +__webpack_unused_export__ = ({ value: true }); +const chalk = __nccwpck_require__(1854); +const supportsColor = __nccwpck_require__(62901); +const spinner_1 = __nccwpck_require__(85865); +function color(s, frameIndex) { + const prideColors = [ + chalk.keyword('pink'), + chalk.red, + chalk.keyword('orange'), + chalk.yellow, + chalk.green, + chalk.cyan, + chalk.blue, + chalk.magenta, + ]; + if (!supportsColor) + return s; + const has256 = supportsColor.stdout ? supportsColor.stdout.has256 : (process.env.TERM || '').includes('256'); + const prideColor = prideColors[frameIndex] || prideColors[0]; + return has256 ? prideColor(s) : chalk.magenta(s); +} +class PrideSpinnerAction extends spinner_1.default { + _frame() { + const frame = this.frames[this.frameIndex]; + this.frameIndex = ++this.frameIndex % this.frames.length; + return color(frame, this.frameIndex); } } -exports.ExitError = ExitError; +exports.Z = PrideSpinnerAction; /***/ }), -/***/ 37053: +/***/ 46521: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var __webpack_unused_export__; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ModuleLoadError = void 0; -const cli_1 = __nccwpck_require__(68463); -class ModuleLoadError extends cli_1.CLIError { - constructor(message) { - super(`[MODULE_NOT_FOUND] ${message}`, { exit: 1 }); - this.code = 'MODULE_NOT_FOUND'; - this.name = 'ModuleLoadError'; +__webpack_unused_export__ = ({ value: true }); +const base_1 = __nccwpck_require__(38174); +class SimpleAction extends base_1.ActionBase { + constructor() { + super(...arguments); + this.type = 'simple'; + } + _start() { + const task = this.task; + if (!task) + return; + this._render(task.action, task.status); + } + _pause(icon) { + if (icon) + this._updateStatus(icon); + else + this._flush(); + } + _resume() { } + _updateStatus(status, prevStatus, newline = false) { + const task = this.task; + if (!task) + return; + if (task.active && !prevStatus) + this._write(this.std, ` ${status}`); + else + this._write(this.std, `${task.action}... ${status}`); + if (newline || !prevStatus) + this._flush(); + } + _stop(status) { + const task = this.task; + if (!task) + return; + this._updateStatus(status, task.status, true); + } + _render(action, status) { + const task = this.task; + if (!task) + return; + if (task.active) + this._flush(); + this._write(this.std, status ? `${action}... ${status}` : `${action}...`); + } + _flush() { + this._write(this.std, '\n'); + this._flushStdout(); } } -exports.ModuleLoadError = ModuleLoadError; +exports.Z = SimpleAction; /***/ }), -/***/ 46914: +/***/ 85865: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +// tslint:disable restrict-plus-operands Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.applyPrettyPrintOptions = void 0; -const wrap = __nccwpck_require__(59824); -const indent = __nccwpck_require__(98043); -const screen = __nccwpck_require__(12051); -const config_1 = __nccwpck_require__(75383); -function applyPrettyPrintOptions(error, options) { - const prettyErrorKeys = ['message', 'code', 'ref', 'suggestions']; - for (const key of prettyErrorKeys) { - const applyOptionsKey = !(key in error) && options[key]; - if (applyOptionsKey) { - error[key] = options[key]; - } - } - return error; +const chalk = __nccwpck_require__(1854); +const supportsColor = __nccwpck_require__(62901); +const deps_1 = __nccwpck_require__(10158); +const base_1 = __nccwpck_require__(38174); +/* eslint-disable-next-line node/no-missing-require */ +const spinners = __nccwpck_require__(39861); +function color(s) { + if (!supportsColor) + return s; + const has256 = supportsColor.stdout ? supportsColor.stdout.has256 : (process.env.TERM || '').includes('256'); + return has256 ? `\u001B[38;5;104m${s}${deps_1.default.ansiStyles.reset.open}` : chalk.magenta(s); } -exports.applyPrettyPrintOptions = applyPrettyPrintOptions; -const formatSuggestions = (suggestions) => { - const label = 'Try this:'; - if (!suggestions || suggestions.length === 0) - return undefined; - if (suggestions.length === 1) - return `${label} ${suggestions[0]}`; - const multiple = suggestions.map(suggestion => `* ${suggestion}`).join('\n'); - return `${label}\n${indent(multiple, 2)}`; -}; -function prettyPrint(error) { - if (config_1.config.debug) { - return error.stack; +class SpinnerAction extends base_1.ActionBase { + constructor() { + super(); + this.type = 'spinner'; + this.frames = spinners[process.platform === 'win32' ? 'line' : 'dots2'].frames; + this.frameIndex = 0; + } + _start() { + this._reset(); + if (this.spinner) + clearInterval(this.spinner); + this._render(); + this.spinner = setInterval(icon => this._render.bind(this)(icon), process.platform === 'win32' ? 500 : 100, 'spinner'); + const interval = this.spinner; + interval.unref(); + } + _stop(status) { + if (this.task) + this.task.status = status; + if (this.spinner) + clearInterval(this.spinner); + this._render(); + this.output = undefined; + } + _pause(icon) { + if (this.spinner) + clearInterval(this.spinner); + this._reset(); + if (icon) + this._render(` ${icon}`); + this.output = undefined; + } + _frame() { + const frame = this.frames[this.frameIndex]; + this.frameIndex = ++this.frameIndex % this.frames.length; + return color(frame); + } + _render(icon) { + const task = this.task; + if (!task) + return; + this._reset(); + this._flushStdout(); + const frame = icon === 'spinner' ? ` ${this._frame()}` : icon || ''; + const status = task.status ? ` ${task.status}` : ''; + this.output = `${task.action}...${frame}${status}\n`; + this._write(this.std, this.output); + } + _reset() { + if (!this.output) + return; + const lines = this._lines(this.output); + this._write(this.std, deps_1.default.ansiEscapes.cursorLeft + deps_1.default.ansiEscapes.cursorUp(lines) + deps_1.default.ansiEscapes.eraseDown); + this.output = undefined; + } + _lines(s) { + return deps_1.default + .stripAnsi(s) + .split('\n') + .map(l => Math.ceil(l.length / deps_1.default.screen.errtermwidth)) + .reduce((c, i) => c + i, 0); } - const { message, code, suggestions, ref, name: errorSuffix, bang } = error; - // errorSuffix is pulled from the 'name' property on CLIError - // and is like either Error or Warning - const formattedHeader = message ? `${errorSuffix || 'Error'}: ${message}` : undefined; - const formattedCode = code ? `Code: ${code}` : undefined; - const formattedSuggestions = formatSuggestions(suggestions); - const formattedReference = ref ? `Reference: ${ref}` : undefined; - const formatted = [formattedHeader, formattedCode, formattedSuggestions, formattedReference] - .filter(Boolean) - .join('\n'); - let output = wrap(formatted, screen.errtermwidth - 6, { trim: false, hard: true }); - output = indent(output, 3); - output = indent(output, 1, { indent: bang || '', includeEmptyLines: true }); - output = indent(output, 1); - return output; } -exports["default"] = prettyPrint; +exports["default"] = SpinnerAction; /***/ }), -/***/ 77463: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 39861: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.handle = void 0; -/* eslint-disable no-process-exit */ -/* eslint-disable unicorn/no-process-exit */ -const config_1 = __nccwpck_require__(75383); -const pretty_print_1 = __nccwpck_require__(46914); -const _1 = __nccwpck_require__(34630); -const clean = __nccwpck_require__(27972); -const cli_1 = __nccwpck_require__(68463); -const handle = (err) => { - var _a, _b, _c; - try { - if (!err) - err = new cli_1.CLIError('no error?'); - if (err.message === 'SIGINT') - process.exit(1); - const shouldPrint = !(err instanceof _1.ExitError); - const pretty = (0, pretty_print_1.default)(err); - const stack = clean(err.stack || '', { pretty: true }); - if (shouldPrint) { - console.error(pretty ? pretty : stack); - } - const exitCode = ((_a = err.oclif) === null || _a === void 0 ? void 0 : _a.exit) !== undefined && ((_b = err.oclif) === null || _b === void 0 ? void 0 : _b.exit) !== false ? (_c = err.oclif) === null || _c === void 0 ? void 0 : _c.exit : 1; - if (config_1.config.errorLogger && err.code !== 'EEXIT') { - if (stack) { - config_1.config.errorLogger.log(stack); - } - config_1.config.errorLogger.flush() - .then(() => process.exit(exitCode)) - .catch(console.error); - } - else - process.exit(exitCode); - } - catch (error) { - console.error(err.stack); - console.error(error.stack); - process.exit(1); - } +module.exports = { + hexagon: { + interval: 400, + frames: ['⬡', '⬢'], + }, + dots: { + interval: 80, + frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], + }, + dots2: { + interval: 80, + frames: ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'], + }, + dots3: { + interval: 80, + frames: ['⠋', '⠙', '⠚', '⠞', '⠖', '⠦', '⠴', '⠲', '⠳', '⠓'], + }, + dots4: { + interval: 80, + frames: ['⠄', '⠆', '⠇', '⠋', '⠙', '⠸', '⠰', '⠠', '⠰', '⠸', '⠙', '⠋', '⠇', '⠆'], + }, + dots5: { + interval: 80, + frames: ['⠋', '⠙', '⠚', '⠒', '⠂', '⠂', '⠒', '⠲', '⠴', '⠦', '⠖', '⠒', '⠐', '⠐', '⠒', '⠓', '⠋'], + }, + dots6: { + interval: 80, + frames: [ + '⠁', + '⠉', + '⠙', + '⠚', + '⠒', + '⠂', + '⠂', + '⠒', + '⠲', + '⠴', + '⠤', + '⠄', + '⠄', + '⠤', + '⠴', + '⠲', + '⠒', + '⠂', + '⠂', + '⠒', + '⠚', + '⠙', + '⠉', + '⠁', + ], + }, + dots7: { + interval: 80, + frames: [ + '⠈', + '⠉', + '⠋', + '⠓', + '⠒', + '⠐', + '⠐', + '⠒', + '⠖', + '⠦', + '⠤', + '⠠', + '⠠', + '⠤', + '⠦', + '⠖', + '⠒', + '⠐', + '⠐', + '⠒', + '⠓', + '⠋', + '⠉', + '⠈', + ], + }, + dots8: { + interval: 80, + frames: [ + '⠁', + '⠁', + '⠉', + '⠙', + '⠚', + '⠒', + '⠂', + '⠂', + '⠒', + '⠲', + '⠴', + '⠤', + '⠄', + '⠄', + '⠤', + '⠠', + '⠠', + '⠤', + '⠦', + '⠖', + '⠒', + '⠐', + '⠐', + '⠒', + '⠓', + '⠋', + '⠉', + '⠈', + '⠈', + ], + }, + dots9: { + interval: 80, + frames: ['⢹', '⢺', '⢼', '⣸', '⣇', '⡧', '⡗', '⡏'], + }, + dots10: { + interval: 80, + frames: ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'], + }, + dots11: { + interval: 100, + frames: ['⠁', '⠂', '⠄', '⡀', '⢀', '⠠', '⠐', '⠈'], + }, + line: { + interval: 130, + frames: ['-', '\\', '|', '/'], + }, + line2: { + interval: 100, + frames: ['⠂', '-', '–', '—', '–', '-'], + }, + pipe: { + interval: 100, + frames: ['┤', '┘', '┴', '└', '├', '┌', '┬', '┐'], + }, + simpleDots: { + interval: 400, + frames: ['. ', '.. ', '...', ' '], + }, + simpleDotsScrolling: { + interval: 200, + frames: ['. ', '.. ', '...', ' ..', ' .', ' '], + }, + star: { + interval: 70, + frames: ['✶', '✸', '✹', '✺', '✹', '✷'], + }, + star2: { + interval: 80, + frames: ['+', 'x', '*'], + }, + flip: { + interval: 70, + frames: ['_', '_', '_', '-', '`', '`', '\'', '´', '-', '_', '_', '_'], + }, + hamburger: { + interval: 100, + frames: ['☱', '☲', '☴'], + }, + growVertical: { + interval: 120, + frames: ['▁', '▃', '▄', '▅', '▆', '▇', '▆', '▅', '▄', '▃'], + }, + growHorizontal: { + interval: 120, + frames: ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '▊', '▋', '▌', '▍', '▎'], + }, + balloon: { + interval: 140, + frames: [' ', '.', 'o', 'O', '@', '*', ' '], + }, + balloon2: { + interval: 120, + frames: ['.', 'o', 'O', '°', 'O', 'o', '.'], + }, + noise: { + interval: 100, + frames: ['▓', '▒', '░'], + }, + bounce: { + interval: 120, + frames: ['⠁', '⠂', '⠄', '⠂'], + }, + boxBounce: { + interval: 120, + frames: ['▖', '▘', '▝', '▗'], + }, + boxBounce2: { + interval: 100, + frames: ['▌', '▀', '▐', '▄'], + }, + triangle: { + interval: 50, + frames: ['◢', '◣', '◤', '◥'], + }, + arc: { + interval: 100, + frames: ['◜', '◠', '◝', '◞', '◡', '◟'], + }, + circle: { + interval: 120, + frames: ['◡', '⊙', '◠'], + }, + squareCorners: { + interval: 180, + frames: ['◰', '◳', '◲', '◱'], + }, + circleQuarters: { + interval: 120, + frames: ['◴', '◷', '◶', '◵'], + }, + circleHalves: { + interval: 50, + frames: ['◐', '◓', '◑', '◒'], + }, + squish: { + interval: 100, + frames: ['╫', '╪'], + }, + toggle: { + interval: 250, + frames: ['⊶', '⊷'], + }, + toggle2: { + interval: 80, + frames: ['▫', '▪'], + }, + toggle3: { + interval: 120, + frames: ['□', '■'], + }, + toggle4: { + interval: 100, + frames: ['■', '□', '▪', '▫'], + }, + toggle5: { + interval: 100, + frames: ['▮', '▯'], + }, + toggle6: { + interval: 300, + frames: ['ဝ', '၀'], + }, + toggle7: { + interval: 80, + frames: ['⦾', '⦿'], + }, + toggle8: { + interval: 100, + frames: ['◍', '◌'], + }, + toggle9: { + interval: 100, + frames: ['◉', '◎'], + }, + toggle10: { + interval: 100, + frames: ['㊂', '㊀', '㊁'], + }, + toggle11: { + interval: 50, + frames: ['⧇', '⧆'], + }, + toggle12: { + interval: 120, + frames: ['☗', '☖'], + }, + toggle13: { + interval: 80, + frames: ['=', '*', '-'], + }, + arrow: { + interval: 100, + frames: ['←', '↖', '↑', '↗', '→', '↘', '↓', '↙'], + }, + arrow2: { + interval: 80, + frames: ['⬆️ ', '↗️ ', '➡️ ', '↘️ ', '⬇️ ', '↙️ ', '⬅️ ', '↖️ '], + }, + arrow3: { + interval: 120, + frames: ['▹▹▹▹▹', '▸▹▹▹▹', '▹▸▹▹▹', '▹▹▸▹▹', '▹▹▹▸▹', '▹▹▹▹▸'], + }, + bouncingBar: { + interval: 80, + frames: ['[ ]', '[ =]', '[ ==]', '[ ===]', '[====]', '[=== ]', '[== ]', '[= ]'], + }, + bouncingBall: { + interval: 80, + frames: [ + '( ● )', + '( ● )', + '( ● )', + '( ● )', + '( ●)', + '( ● )', + '( ● )', + '( ● )', + '( ● )', + '(● )', + ], + }, + smiley: { + interval: 200, + frames: ['😄 ', '😝 '], + }, + monkey: { + interval: 300, + frames: ['🙈 ', '🙈 ', '🙉 ', '🙊 '], + }, + hearts: { + interval: 100, + frames: ['💛 ', '💙 ', '💜 ', '💚 ', '❤️ '], + }, + clock: { + interval: 100, + frames: ['🕐 ', '🕑 ', '🕒 ', '🕓 ', '🕔 ', '🕕 ', '🕖 ', '🕗 ', '🕘 ', '🕙 ', '🕚 '], + }, + earth: { + interval: 180, + frames: ['🌍 ', '🌎 ', '🌏 '], + }, + moon: { + interval: 80, + frames: ['🌑 ', '🌒 ', '🌓 ', '🌔 ', '🌕 ', '🌖 ', '🌗 ', '🌘 '], + }, + runner: { + interval: 140, + frames: ['🚶 ', '🏃 '], + }, + pong: { + interval: 80, + frames: [ + '▐⠂ ▌', + '▐⠈ ▌', + '▐ ⠂ ▌', + '▐ ⠠ ▌', + '▐ ⡀ ▌', + '▐ ⠠ ▌', + '▐ ⠂ ▌', + '▐ ⠈ ▌', + '▐ ⠂ ▌', + '▐ ⠠ ▌', + '▐ ⡀ ▌', + '▐ ⠠ ▌', + '▐ ⠂ ▌', + '▐ ⠈ ▌', + '▐ ⠂▌', + '▐ ⠠▌', + '▐ ⡀▌', + '▐ ⠠ ▌', + '▐ ⠂ ▌', + '▐ ⠈ ▌', + '▐ ⠂ ▌', + '▐ ⠠ ▌', + '▐ ⡀ ▌', + '▐ ⠠ ▌', + '▐ ⠂ ▌', + '▐ ⠈ ▌', + '▐ ⠂ ▌', + '▐ ⠠ ▌', + '▐ ⡀ ▌', + '▐⠠ ▌', + ], + }, }; -exports.handle = handle; /***/ }), -/***/ 34630: +/***/ 8048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// tslint:disable no-console Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.warn = exports.error = exports.exit = exports.config = exports.Logger = exports.CLIError = exports.ModuleLoadError = exports.ExitError = exports.handle = void 0; -var handle_1 = __nccwpck_require__(77463); -Object.defineProperty(exports, "handle", ({ enumerable: true, get: function () { return handle_1.handle; } })); -var exit_1 = __nccwpck_require__(30950); -Object.defineProperty(exports, "ExitError", ({ enumerable: true, get: function () { return exit_1.ExitError; } })); -var module_load_1 = __nccwpck_require__(37053); -Object.defineProperty(exports, "ModuleLoadError", ({ enumerable: true, get: function () { return module_load_1.ModuleLoadError; } })); -var cli_1 = __nccwpck_require__(68463); -Object.defineProperty(exports, "CLIError", ({ enumerable: true, get: function () { return cli_1.CLIError; } })); -var logger_1 = __nccwpck_require__(69599); -Object.defineProperty(exports, "Logger", ({ enumerable: true, get: function () { return logger_1.Logger; } })); -var config_1 = __nccwpck_require__(75383); -Object.defineProperty(exports, "config", ({ enumerable: true, get: function () { return config_1.config; } })); -const config_2 = __nccwpck_require__(75383); -const cli_2 = __nccwpck_require__(68463); -const exit_2 = __nccwpck_require__(30950); -const pretty_print_1 = __nccwpck_require__(46914); -function exit(code = 0) { - throw new exit_2.ExitError(code); -} -exports.exit = exit; -function error(input, options = {}) { - var _a; - let err; - if (typeof input === 'string') { - err = new cli_2.CLIError(input, options); - } - else if (input instanceof Error) { - err = (0, cli_2.addOclifExitCode)(input, options); - } - else { - throw new TypeError('first argument must be a string or instance of Error'); +exports.config = exports.Config = void 0; +const semver = __nccwpck_require__(11383); +const version = semver.parse((__nccwpck_require__(56193).version)); +const g = global; +const globals = g['cli-ux'] || (g['cli-ux'] = {}); +const actionType = (Boolean(process.stderr.isTTY) && + !process.env.CI && + !['dumb', 'emacs-color'].includes(process.env.TERM) && + 'spinner') || 'simple'; +/* eslint-disable node/no-missing-require */ +const Action = actionType === 'spinner' ? (__nccwpck_require__(85865)["default"]) : (__nccwpck_require__(46521)/* ["default"] */ .Z); +const PrideAction = actionType === 'spinner' ? (__nccwpck_require__(9749)/* ["default"] */ .Z) : (__nccwpck_require__(46521)/* ["default"] */ .Z); +/* eslint-enable node/no-missing-require */ +class Config { + constructor() { + this.outputLevel = 'info'; + this.action = new Action(); + this.prideAction = new PrideAction(); + this.errorsHandled = false; + this.showStackTrace = true; } - err = (0, pretty_print_1.applyPrettyPrintOptions)(err, options); - if (options.exit === false) { - const message = (0, pretty_print_1.default)(err); - console.error(message); - if (config_2.config.errorLogger) - config_2.config.errorLogger.log((_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : ''); + get debug() { + return globals.debug || process.env.DEBUG === '*'; } - else - throw err; -} -exports.error = error; -function warn(input) { - var _a; - let err; - if (typeof input === 'string') { - err = new cli_2.CLIError.Warn(input); + set debug(v) { + globals.debug = v; } - else if (input instanceof Error) { - err = (0, cli_2.addOclifExitCode)(input); + get context() { + return globals.context || {}; } - else { - throw new TypeError('first argument must be a string or instance of Error'); + set context(v) { + globals.context = v; } - const message = (0, pretty_print_1.default)(err); - console.error(message); - if (config_2.config.errorLogger) - config_2.config.errorLogger.log((_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : ''); } -exports.warn = warn; +exports.Config = Config; +function fetch() { + if (globals[version.major]) + return globals[version.major]; + globals[version.major] = new Config(); + return globals[version.major]; +} +exports.config = fetch(); +exports["default"] = exports.config; /***/ }), -/***/ 69599: +/***/ 10158: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Logger = void 0; -const path = __nccwpck_require__(71017); -const timestamp = () => new Date().toISOString(); -let timer; -const wait = (ms) => new Promise(resolve => { - if (timer) - timer.unref(); - timer = setTimeout(() => resolve(null), ms); -}); -function chomp(s) { - if (s.endsWith('\n')) - return s.replace(/\n$/, ''); - return s; -} -class Logger { - // eslint-disable-next-line no-useless-constructor - constructor(file) { - this.file = file; - this.flushing = Promise.resolve(); - this.buffer = []; - } - log(msg) { - const stripAnsi = __nccwpck_require__(45591); - msg = stripAnsi(chomp(msg)); - const lines = msg.split('\n').map(l => `${timestamp()} ${l}`.trimEnd()); - this.buffer.push(...lines); - // tslint:disable-next-line no-console - this.flush(50).catch(console.error); - } - async flush(waitForMs = 0) { - await wait(waitForMs); - this.flushing = this.flushing.then(async () => { - if (this.buffer.length === 0) - return; - const mylines = this.buffer; - this.buffer = []; - const fs = __nccwpck_require__(39035); - await fs.mkdirp(path.dirname(this.file)); - await fs.appendFile(this.file, mylines.join('\n') + '\n'); - }); - await this.flushing; - } -} -exports.Logger = Logger; - - -/***/ }), - -/***/ 78251: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.help = exports.version = exports.url = exports.integer = exports.boolean = exports.string = exports["enum"] = exports.option = exports.build = void 0; -const Parser = __nccwpck_require__(44195); -function build(defaults) { - return Parser.flags.build(defaults); -} -exports.build = build; -function option(options) { - return build(options)(); -} -exports.option = option; -const _enum = (opts) => { - return build({ - async parse(input) { - if (!opts.options.includes(input)) - throw new Error(`Expected --${this.name}=${input} to be one of: ${opts.options.join(', ')}`); - return input; - }, - helpValue: `(${opts.options.join('|')})`, - ...opts, - })(); -}; -exports["enum"] = _enum; -const stringFlag = build({}); -exports.string = stringFlag; -var parser_1 = __nccwpck_require__(44195); -Object.defineProperty(exports, "boolean", ({ enumerable: true, get: function () { return parser_1.boolean; } })); -Object.defineProperty(exports, "integer", ({ enumerable: true, get: function () { return parser_1.integer; } })); -Object.defineProperty(exports, "url", ({ enumerable: true, get: function () { return parser_1.url; } })); -const version = (opts = {}) => { - return Parser.flags.boolean({ - description: 'Show CLI version.', - ...opts, - parse: async (_, cmd) => { - cmd.log(cmd.config.userAgent); - cmd.exit(0); - }, - }); -}; -exports.version = version; -const help = (opts = {}) => { - return Parser.flags.boolean({ - description: 'Show CLI help.', - ...opts, - parse: async (_, cmd) => { - cmd._help(); - }, - }); +/* eslint-disable node/no-missing-require */ +exports["default"] = { + get stripAnsi() { + return __nccwpck_require__(45591); + }, + get ansiStyles() { + return __nccwpck_require__(14169); + }, + get ansiEscapes() { + return __nccwpck_require__(18512); + }, + get passwordPrompt() { + return __nccwpck_require__(71719); + }, + get screen() { + return __nccwpck_require__(55463); + }, + get open() { + return (__nccwpck_require__(81951)/* ["default"] */ .Z); + }, + get prompt() { + return __nccwpck_require__(88935); + }, + get styledObject() { + return (__nccwpck_require__(68002)/* ["default"] */ .Z); + }, + get styledHeader() { + return (__nccwpck_require__(55260)/* ["default"] */ .Z); + }, + get styledJSON() { + return (__nccwpck_require__(97995)/* ["default"] */ .Z); + }, + get table() { + return (__nccwpck_require__(67729).table); + }, + get tree() { + return (__nccwpck_require__(68363)/* ["default"] */ .ZP); + }, + get wait() { + return (__nccwpck_require__(48871)/* ["default"] */ .Z); + }, + get progress() { + return (__nccwpck_require__(14594)/* ["default"] */ .Z); + }, }; -exports.help = help; /***/ }), -/***/ 40713: +/***/ 32367: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.newArg = void 0; -function newArg(arg) { - return { - parse: (i) => i, - ...arg, - required: Boolean(arg.required), - }; +exports.ExitError = void 0; +class ExitError extends Error { + constructor(status, error) { + const code = 'EEXIT'; + super(error ? error.message : `${code}: ${status}`); + this.error = error; + this['cli-ux'] = { exit: status }; + this.code = code; + } } -exports.newArg = newArg; - - -/***/ }), - -/***/ 72774: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = () => { - const cache = {}; - return { - add(name, fn) { - Object.defineProperty(this, name, { - enumerable: true, - get: () => { - cache[name] = cache[name] || fn(); - return cache[name]; - }, - }); - return this; - }, - }; -}; +exports.ExitError = ExitError; /***/ }), -/***/ 27916: +/***/ 32266: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ArgInvalidOptionError = exports.FlagInvalidOptionError = exports.UnexpectedArgsError = exports.RequiredFlagError = exports.RequiredArgsError = exports.InvalidArgsSpecError = exports.CLIParseError = exports.CLIError = void 0; -const errors_1 = __nccwpck_require__(34630); -const deps_1 = __nccwpck_require__(72774); -var errors_2 = __nccwpck_require__(34630); -Object.defineProperty(exports, "CLIError", ({ enumerable: true, get: function () { return errors_2.CLIError; } })); -// eslint-disable-next-line new-cap -const m = (0, deps_1.default)() - // eslint-disable-next-line node/no-missing-require - .add('help', () => __nccwpck_require__(85766)) - // eslint-disable-next-line node/no-missing-require - .add('list', () => __nccwpck_require__(55366)); -class CLIParseError extends errors_1.CLIError { - constructor(options) { - options.message += '\nSee more help with --help'; - super(options.message); - this.parse = options.parse; +exports.Table = exports.ExitError = exports.Config = exports.ActionBase = exports.config = exports.ux = void 0; +const Errors = __nccwpck_require__(34630); +const util = __nccwpck_require__(73837); +const base_1 = __nccwpck_require__(38174); +Object.defineProperty(exports, "ActionBase", ({ enumerable: true, get: function () { return base_1.ActionBase; } })); +const config_1 = __nccwpck_require__(8048); +Object.defineProperty(exports, "config", ({ enumerable: true, get: function () { return config_1.config; } })); +Object.defineProperty(exports, "Config", ({ enumerable: true, get: function () { return config_1.Config; } })); +const deps_1 = __nccwpck_require__(10158); +const exit_1 = __nccwpck_require__(32367); +Object.defineProperty(exports, "ExitError", ({ enumerable: true, get: function () { return exit_1.ExitError; } })); +const Table = __nccwpck_require__(67729); +exports.Table = Table; +const hyperlinker = __nccwpck_require__(59584); +function timeout(p, ms) { + function wait(ms, unref = false) { + return new Promise(resolve => { + const t = setTimeout(() => resolve(null), ms); + if (unref) + t.unref(); + }); } + return Promise.race([p, wait(ms, true).then(() => exports.ux.error('timed out'))]); } -exports.CLIParseError = CLIParseError; -class InvalidArgsSpecError extends CLIParseError { - constructor({ args, parse }) { - let message = 'Invalid argument spec'; - const namedArgs = args.filter(a => a.name); - if (namedArgs.length > 0) { - const list = m.list.renderList(namedArgs.map(a => [`${a.name} (${a.required ? 'required' : 'optional'})`, a.description])); - message += `:\n${list}`; - } - super({ parse, message }); - this.args = args; - } +async function flush() { + const p = new Promise(resolve => { + process.stdout.once('drain', () => resolve(null)); + }); + process.stdout.write(''); + return p; } -exports.InvalidArgsSpecError = InvalidArgsSpecError; -class RequiredArgsError extends CLIParseError { - constructor({ args, parse }) { - let message = `Missing ${args.length} required arg${args.length === 1 ? '' : 's'}`; - const namedArgs = args.filter(a => a.name); - if (namedArgs.length > 0) { - const list = m.list.renderList(namedArgs.map(a => [a.name, a.description])); - message += `:\n${list}`; +exports.ux = { + config: config_1.config, + warn: Errors.warn, + error: Errors.error, + exit: Errors.exit, + get prompt() { + return deps_1.default.prompt.prompt; + }, + /** + * "press anykey to continue" + */ + get anykey() { + return deps_1.default.prompt.anykey; + }, + get confirm() { + return deps_1.default.prompt.confirm; + }, + get action() { + return config_1.config.action; + }, + get prideAction() { + return config_1.config.prideAction; + }, + styledObject(obj, keys) { + exports.ux.info(deps_1.default.styledObject(obj, keys)); + }, + get styledHeader() { + return deps_1.default.styledHeader; + }, + get styledJSON() { + return deps_1.default.styledJSON; + }, + get table() { + return deps_1.default.table; + }, + get tree() { + return deps_1.default.tree; + }, + get open() { + return deps_1.default.open; + }, + get wait() { + return deps_1.default.wait; + }, + get progress() { + return deps_1.default.progress; + }, + async done() { + config_1.config.action.stop(); + // await flushStdout() + }, + trace(format, ...args) { + if (this.config.outputLevel === 'trace') { + process.stdout.write(util.format(format, ...args) + '\n'); } - super({ parse, message }); - this.args = args; - } -} -exports.RequiredArgsError = RequiredArgsError; -class RequiredFlagError extends CLIParseError { - constructor({ flag, parse }) { - const usage = m.list.renderList(m.help.flagUsages([flag], { displayRequired: false })); - const message = `Missing required flag:\n${usage}`; - super({ parse, message }); - this.flag = flag; - } -} -exports.RequiredFlagError = RequiredFlagError; -class UnexpectedArgsError extends CLIParseError { - constructor({ parse, args }) { - const message = `Unexpected argument${args.length === 1 ? '' : 's'}: ${args.join(', ')}`; - super({ parse, message }); - this.args = args; - } -} -exports.UnexpectedArgsError = UnexpectedArgsError; -class FlagInvalidOptionError extends CLIParseError { - constructor(flag, input) { - const message = `Expected --${flag.name}=${input} to be one of: ${flag.options.join(', ')}`; - super({ parse: {}, message }); - } -} -exports.FlagInvalidOptionError = FlagInvalidOptionError; -class ArgInvalidOptionError extends CLIParseError { - constructor(arg, input) { - const message = `Expected ${input} to be one of: ${arg.options.join(', ')}`; - super({ parse: {}, message }); - } -} -exports.ArgInvalidOptionError = ArgInvalidOptionError; - - -/***/ }), - -/***/ 96478: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -// tslint:disable interface-over-type-literal -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultFlags = exports.string = exports.option = exports.url = exports.integer = exports.boolean = exports.build = void 0; -const url_1 = __nccwpck_require__(57310); -function build(defaults) { - return (options = {}) => { - return { - parse: async (i, _) => i, - ...defaults, - ...options, - input: [], - multiple: Boolean(options.multiple), - type: 'option', - }; - }; -} -exports.build = build; -function boolean(options = {}) { - return { - parse: async (b, _) => b, - ...options, - allowNo: Boolean(options.allowNo), - type: 'boolean', - }; -} -exports.boolean = boolean; -exports.integer = build({ - parse: async (input) => { - if (!/^-?\d+$/.test(input)) - throw new Error(`Expected an integer but received: ${input}`); - return Number.parseInt(input, 10); }, -}); -/** - * Initializes a string as a URL. Throws an error - * if the string is not a valid URL. - */ -exports.url = build({ - parse: async (input) => { - try { - return new url_1.URL(input); + debug(format, ...args) { + if (['trace', 'debug'].includes(this.config.outputLevel)) { + process.stdout.write(util.format(format, ...args) + '\n'); } - catch { - throw new Error(`Expected a valid url but received: ${input}`); + }, + info(format, ...args) { + process.stdout.write(util.format(format, ...args) + '\n'); + }, + log(format, ...args) { + this.info(format || '', ...args); + }, + url(text, uri, params = {}) { + const supports = __nccwpck_require__(18824); + if (supports.stdout) { + this.log(hyperlinker(text, uri, params)); + } + else { + this.log(uri); } }, -}); -function option(options) { - return build(options)(); -} -exports.option = option; -const stringFlag = build({}); -exports.string = stringFlag; -exports.defaultFlags = { - color: boolean({ allowNo: true }), + annotation(text, annotation) { + const supports = __nccwpck_require__(18824); + if (supports.stdout) { + // \u001b]8;;https://google.com\u0007sometext\u001b]8;;\u0007 + this.log(`\u001B]1337;AddAnnotation=${text.length}|${annotation}\u0007${text}`); + } + else { + this.log(text); + } + }, + async flush() { + await timeout(flush(), 10000); + }, +}; +const cliuxProcessExitHandler = async () => { + try { + await exports.ux.done(); + } + catch (error) { + // tslint:disable no-console + console.error(error); + process.exitCode = 1; + } }; +// to avoid MaxListenersExceededWarning +// only attach named listener once +const cliuxListener = process.listeners('exit').find(fn => fn.name === cliuxProcessExitHandler.name); +if (!cliuxListener) { + process.once('exit', cliuxProcessExitHandler); +} /***/ }), -/***/ 85766: +/***/ 81951: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var __webpack_unused_export__; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.flagUsages = exports.flagUsage = void 0; -const deps_1 = __nccwpck_require__(72774); -// eslint-disable-next-line new-cap -const m = (0, deps_1.default)() - .add('chalk', () => __nccwpck_require__(1854)) - // eslint-disable-next-line node/no-missing-require - .add('util', () => __nccwpck_require__(30138)); -function flagUsage(flag, options = {}) { - const label = []; - if (flag.helpLabel) { - label.push(flag.helpLabel); +__webpack_unused_export__ = ({ value: true }); +// this code is largely taken from opn +const childProcess = __nccwpck_require__(32081); +const isWsl = __nccwpck_require__(52559); +function open(target, opts = {}) { + // opts = {wait: true, ...opts} + let cmd; + let appArgs = []; + let args = []; + const cpOpts = {}; + if (Array.isArray(opts.app)) { + appArgs = opts.app.slice(1); + opts.app = opts.app[0]; + } + if (process.platform === 'darwin') { + cmd = 'open'; + // if (opts.wait) { + // args.push('-W') + // } + if (opts.app) { + args.push('-a', opts.app); + } + } + else if (process.platform === 'win32' || isWsl) { + cmd = 'cmd' + (isWsl ? '.exe' : ''); + args.push('/c', 'start', '""', '/b'); + target = target.replace(/&/g, '^&'); + // if (opts.wait) { + // args.push('/wait') + // } + if (opts.app) { + args.push(opts.app); + } + if (appArgs.length > 0) { + args = [...args, ...appArgs]; + } } else { - if (flag.char) - label.push(`-${flag.char}`); - if (flag.name) - label.push(` --${flag.name}`); + cmd = opts.app ? opts.app : 'xdg-open'; + if (appArgs.length > 0) { + args = [...args, ...appArgs]; + } + // if (!opts.wait) { + // `xdg-open` will block the process unless + // stdio is ignored and it's detached from the parent + // even if it's unref'd + cpOpts.stdio = 'ignore'; + cpOpts.detached = true; + // } } - const usage = flag.type === 'option' ? ` ${flag.name.toUpperCase()}` : ''; - let description = flag.summary || flag.description || ''; - if (options.displayRequired && flag.required) - description = `(required) ${description}`; - description = description ? m.chalk.dim(description) : undefined; - return [` ${label.join(',').trim()}${usage}`, description]; -} -exports.flagUsage = flagUsage; -function flagUsages(flags, options = {}) { - if (flags.length === 0) - return []; - const { sortBy } = m.util; - return sortBy(flags, f => [f.char ? -1 : 1, f.char, f.name]) - .map(f => flagUsage(f, options)); + args.push(target); + if (process.platform === 'darwin' && appArgs.length > 0) { + args.push('--args'); + args = [...args, ...appArgs]; + } + const cp = childProcess.spawn(cmd, args, cpOpts); + return new Promise((resolve, reject) => { + cp.once('error', reject); + cp.once('close', code => { + if (Number.isInteger(code) && code > 0) { + reject(new Error('Exited with code ' + code)); + return; + } + resolve(cp); + }); + }); } -exports.flagUsages = flagUsages; +exports.Z = open; /***/ }), -/***/ 44195: +/***/ 88935: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// tslint:disable interface-over-type-literal Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.url = exports.integer = exports.boolean = exports.parse = exports.flagUsages = exports.flags = exports.args = void 0; -const args = __nccwpck_require__(40713); -exports.args = args; -const deps_1 = __nccwpck_require__(72774); -const flags = __nccwpck_require__(96478); -exports.flags = flags; -const parse_1 = __nccwpck_require__(24813); -var help_1 = __nccwpck_require__(85766); -Object.defineProperty(exports, "flagUsages", ({ enumerable: true, get: function () { return help_1.flagUsages; } })); -// eslint-disable-next-line new-cap -const m = (0, deps_1.default)() - // eslint-disable-next-line node/no-missing-require - .add('validate', () => (__nccwpck_require__(99623)/* .validate */ .G)); -async function parse(argv, options) { - const input = { - argv, - context: options.context, - args: (options.args || []).map((a) => args.newArg(a)), - '--': options['--'], - flags: { - color: flags.defaultFlags.color, - ...((options.flags || {})), - }, - strict: options.strict !== false, +exports.anykey = exports.confirm = exports.prompt = void 0; +const Errors = __nccwpck_require__(34630); +const chalk = __nccwpck_require__(1854); +const config_1 = __nccwpck_require__(8048); +const deps_1 = __nccwpck_require__(10158); +function normal(options, retries = 100) { + if (retries < 0) + throw new Error('no input'); + return new Promise((resolve, reject) => { + let timer; + if (options.timeout) { + timer = setTimeout(() => { + process.stdin.pause(); + reject(new Error('Prompt timeout')); + }, options.timeout); + timer.unref(); + } + process.stdin.setEncoding('utf8'); + process.stderr.write(options.prompt); + process.stdin.resume(); + process.stdin.once('data', b => { + if (timer) + clearTimeout(timer); + process.stdin.pause(); + const data = (typeof b === 'string' ? b : b.toString()).trim(); + if (!options.default && options.required && data === '') { + resolve(normal(options, retries - 1)); + } + else { + resolve(data || options.default); + } + }); + }); +} +function getPrompt(name, type, defaultValue) { + let prompt = '> '; + if (defaultValue && type === 'hide') { + defaultValue = '*'.repeat(defaultValue.length); + } + if (name && defaultValue) + prompt = name + ' ' + chalk.yellow('[' + defaultValue + ']') + ': '; + else if (name) + prompt = `${name}: `; + return prompt; +} +async function single(options) { + var _a; + const raw = process.stdin.isRaw; + if (process.stdin.setRawMode) + process.stdin.setRawMode(true); + options.required = (_a = options.required) !== null && _a !== void 0 ? _a : false; + const response = await normal(options); + if (process.stdin.setRawMode) + process.stdin.setRawMode(Boolean(raw)); + return response; +} +function replacePrompt(prompt) { + process.stderr.write(deps_1.default.ansiEscapes.cursorHide + deps_1.default.ansiEscapes.cursorUp(1) + deps_1.default.ansiEscapes.cursorLeft + prompt + + deps_1.default.ansiEscapes.cursorDown(1) + deps_1.default.ansiEscapes.cursorLeft + deps_1.default.ansiEscapes.cursorShow); +} +function _prompt(name, inputOptions = {}) { + const prompt = getPrompt(name, inputOptions.type, inputOptions.default); + const options = { + isTTY: Boolean(process.env.TERM !== 'dumb' && process.stdin.isTTY), + name, + prompt, + type: 'normal', + required: true, + default: '', + ...inputOptions, }; - const parser = new parse_1.Parser(input); - const output = await parser.parse(); - m.validate({ input, output }); - return output; + switch (options.type) { + case 'normal': + return normal(options); + case 'single': + return single(options); + case 'mask': + return deps_1.default.passwordPrompt(options.prompt, { + method: options.type, + required: options.required, + default: options.default, + }).then((value) => { + replacePrompt(getPrompt(name, 'hide', inputOptions.default)); + return value; + }); + case 'hide': + return deps_1.default.passwordPrompt(options.prompt, { + method: options.type, + required: options.required, + default: options.default, + }); + default: + throw new Error(`unexpected type ${options.type}`); + } } -exports.parse = parse; -const { boolean, integer, url } = flags; -exports.boolean = boolean; -exports.integer = integer; -exports.url = url; +/** + * prompt for input + * @param name - prompt text + * @param options - @see IPromptOptions + * @returns void + */ +function prompt(name, options = {}) { + return config_1.default.action.pauseAsync(() => { + return _prompt(name, options); + }, chalk.cyan('?')); +} +exports.prompt = prompt; +/** + * confirmation prompt (yes/no) + * @param message - confirmation text + * @returns Promise + */ +function confirm(message) { + return config_1.default.action.pauseAsync(async () => { + const confirm = async () => { + const response = (await _prompt(message)).toLowerCase(); + if (['n', 'no'].includes(response)) + return false; + if (['y', 'yes'].includes(response)) + return true; + return confirm(); + }; + return confirm(); + }, chalk.cyan('?')); +} +exports.confirm = confirm; +/** + * "press anykey to continue" + * @param message - optional message to display to user + * @returns Promise + */ +async function anykey(message) { + const tty = Boolean(process.stdin.setRawMode); + if (!message) { + message = tty ? + `Press any key to continue or ${chalk.yellow('q')} to exit` : + `Press enter to continue or ${chalk.yellow('q')} to exit`; + } + const char = await prompt(message, { type: 'single', required: false }); + if (tty) + process.stderr.write('\n'); + if (char === 'q') + Errors.error('quit'); + if (char === '\u0003') + Errors.error('ctrl-c'); + return char; +} +exports.anykey = anykey; /***/ }), -/***/ 55366: +/***/ 55260: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var __webpack_unused_export__; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.renderList = void 0; -const screen_1 = __nccwpck_require__(12051); -const util_1 = __nccwpck_require__(30138); -function linewrap(length, s) { - const lw = __nccwpck_require__(49094); - return lw(length, screen_1.stdtermwidth, { - skipScheme: 'ansi-color', - })(s).trim(); +__webpack_unused_export__ = ({ value: true }); +const chalk = __nccwpck_require__(1854); +const index_1 = __nccwpck_require__(64874); +function styledHeader(header) { + index_1.CliUx.ux.info(chalk.dim('=== ') + chalk.bold(header) + '\n'); } -function renderList(items) { - if (items.length === 0) { - return ''; +exports.Z = styledHeader; + + +/***/ }), + +/***/ 97995: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +var __webpack_unused_export__; + +// tslint:disable restrict-plus-operands +__webpack_unused_export__ = ({ value: true }); +const chalk = __nccwpck_require__(1854); +const index_1 = __nccwpck_require__(64874); +function styledJSON(obj) { + const json = JSON.stringify(obj, null, 2); + if (!chalk.level) { + index_1.CliUx.ux.info(json); + return; } - const maxLength = (0, util_1.maxBy)(items, i => i[0].length)[0].length; - const lines = items.map(i => { - let left = i[0]; - let right = i[1]; - if (!right) { - return left; - } - left = left.padEnd(maxLength); - right = linewrap(maxLength + 2, right); - return `${left} ${right}`; - }); - return lines.join('\n'); + const cardinal = __nccwpck_require__(76021); + const theme = __nccwpck_require__(14054); + index_1.CliUx.ux.info(cardinal.highlight(json, { json: true, theme })); } -exports.renderList = renderList; +exports.Z = styledJSON; /***/ }), -/***/ 24813: +/***/ 68002: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var __webpack_unused_export__; -// tslint:disable interface-over-type-literal -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Parser = void 0; -const deps_1 = __nccwpck_require__(72774); -// eslint-disable-next-line new-cap -const m = (0, deps_1.default)() - // eslint-disable-next-line node/no-missing-require - .add('errors', () => __nccwpck_require__(27916)) - // eslint-disable-next-line node/no-missing-require - .add('util', () => __nccwpck_require__(30138)); -let debug; -try { - // eslint-disable-next-line no-negated-condition - debug = process.env.CLI_FLAGS_DEBUG !== '1' ? () => { } : __nccwpck_require__(38237)('../parser'); -} -catch { - debug = () => { }; -} -const readStdin = async () => { - const { stdin } = process; - let result; - if (stdin.isTTY) - return result; - result = ''; - stdin.setEncoding('utf8'); - for await (const chunk of stdin) { - result += chunk; - } - return result; -}; -class Parser { - constructor(input) { - this.input = input; - this.raw = []; - const { pickBy } = m.util; - this.context = input.context || {}; - this.argv = [...input.argv]; - this._setNames(); - this.booleanFlags = pickBy(input.flags, f => f.type === 'boolean'); - this.metaData = {}; - } - async parse() { - this._debugInput(); - const findLongFlag = (arg) => { - const name = arg.slice(2); - if (this.input.flags[name]) { - return name; - } - if (arg.startsWith('--no-')) { - const flag = this.booleanFlags[arg.slice(5)]; - if (flag && flag.allowNo) - return flag.name; - } - }; - const findShortFlag = (arg) => { - return Object.keys(this.input.flags).find(k => this.input.flags[k].char === arg[1]); - }; - const parseFlag = (arg) => { - const long = arg.startsWith('--'); - const name = long ? findLongFlag(arg) : findShortFlag(arg); - if (!name) { - const i = arg.indexOf('='); - if (i !== -1) { - const sliced = arg.slice(i + 1); - this.argv.unshift(sliced); - const equalsParsed = parseFlag(arg.slice(0, i)); - if (!equalsParsed) { - this.argv.shift(); - } - return equalsParsed; - } - return false; - } - const flag = this.input.flags[name]; - if (flag.type === 'option') { - this.currentFlag = flag; - const input = long || arg.length < 3 ? this.argv.shift() : arg.slice(arg[2] === '=' ? 3 : 2); - if (typeof input !== 'string') { - throw new m.errors.CLIError(`Flag --${name} expects a value`); - } - this.raw.push({ type: 'flag', flag: flag.name, input }); - } - else { - this.raw.push({ type: 'flag', flag: flag.name, input: arg }); - // push the rest of the short characters back on the stack - if (!long && arg.length > 2) { - this.argv.unshift(`-${arg.slice(2)}`); - } - } - return true; - }; - let parsingFlags = true; - while (this.argv.length > 0) { - const input = this.argv.shift(); - if (parsingFlags && input.startsWith('-') && input !== '-') { - // attempt to parse as arg - if (this.input['--'] !== false && input === '--') { - parsingFlags = false; - continue; - } - if (parseFlag(input)) { - continue; - } - // not actually a flag if it reaches here so parse as an arg - } - if (parsingFlags && this.currentFlag && this.currentFlag.multiple) { - this.raw.push({ type: 'flag', flag: this.currentFlag.name, input }); - continue; - } - // not a flag, parse as arg - const arg = this.input.args[this._argTokens.length]; - if (arg) - arg.input = input; - this.raw.push({ type: 'arg', input }); - } - const argv = await this._argv(); - const args = this._args(argv); - const flags = await this._flags(); - this._debugOutput(argv, args, flags); - return { - args, - argv, - flags, - raw: this.raw, - metadata: this.metaData, - }; - } - _args(argv) { - const args = {}; - for (let i = 0; i < this.input.args.length; i++) { - const arg = this.input.args[i]; - args[arg.name] = argv[i]; - } - return args; - } - async _flags() { - const flags = {}; - this.metaData.flags = {}; - for (const token of this._flagTokens) { - const flag = this.input.flags[token.flag]; - if (!flag) - throw new m.errors.CLIError(`Unexpected flag ${token.flag}`); - if (flag.type === 'boolean') { - if (token.input === `--no-${flag.name}`) { - flags[token.flag] = false; - } - else { - flags[token.flag] = true; - } - // eslint-disable-next-line no-await-in-loop - flags[token.flag] = await flag.parse(flags[token.flag], this.context); - } - else { - const input = token.input; - if (flag.options && !flag.options.includes(input)) { - throw new m.errors.FlagInvalidOptionError(flag, input); - } - // eslint-disable-next-line no-await-in-loop - const value = flag.parse ? await flag.parse(input, this.context) : input; - if (flag.multiple) { - flags[token.flag] = flags[token.flag] || []; - flags[token.flag].push(value); - } - else { - flags[token.flag] = value; - } - } - } - for (const k of Object.keys(this.input.flags)) { - const flag = this.input.flags[k]; - if (flags[k]) - continue; - if (flag.type === 'option' && flag.env) { - const input = process.env[flag.env]; - // eslint-disable-next-line no-await-in-loop - if (input) - flags[k] = await flag.parse(input, this.context); - } - if (!(k in flags) && flag.default !== undefined) { - this.metaData.flags[k] = { setFromDefault: true }; - // eslint-disable-next-line no-await-in-loop - const defaultValue = (typeof flag.default === 'function' ? await flag.default({ options: flag, flags, ...this.context }) : flag.default); - const parsedValue = flag.type === 'option' && flag.parse ? - // eslint-disable-next-line no-await-in-loop - await flag.parse(defaultValue, this.context) : - defaultValue; - flags[k] = parsedValue; - } +// tslint:disable +__webpack_unused_export__ = ({ value: true }); +const chalk = __nccwpck_require__(1854); +const util = __nccwpck_require__(73837); +function styledObject(obj, keys) { + const output = []; + const keyLengths = Object.keys(obj).map(key => key.toString().length); + const maxKeyLength = Math.max(...keyLengths) + 2; + function pp(obj) { + if (typeof obj === 'string' || typeof obj === 'number') + return obj; + if (typeof obj === 'object') { + return Object.keys(obj) + .map(k => k + ': ' + util.inspect(obj[k])) + .join(', '); } - return flags; + return util.inspect(obj); } - async _argv() { - const args = []; - const tokens = this._argTokens; - let stdinRead = false; - for (let i = 0; i < Math.max(this.input.args.length, tokens.length); i++) { - const token = tokens[i]; - const arg = this.input.args[i]; - if (token) { - if (arg) { - if (arg.options && !arg.options.includes(token.input)) { - throw new m.errors.ArgInvalidOptionError(arg, token.input); - } - // eslint-disable-next-line no-await-in-loop - args[i] = await arg.parse(token.input); - } - else { - args[i] = token.input; - } - } - else if (!arg.ignoreStdin && !stdinRead) { - // eslint-disable-next-line no-await-in-loop - let stdin = await readStdin(); - if (stdin) { - stdin = stdin.trim(); - args[i] = stdin; - } - stdinRead = true; - } - if (!args[i] && 'default' in arg) { - if (typeof arg.default === 'function') { - // eslint-disable-next-line no-await-in-loop - const f = await arg.default(); - args[i] = f; - } - else { - args[i] = arg.default; + const logKeyValue = (key, value) => { + return `${chalk.blue(key)}:` + ' '.repeat(maxKeyLength - key.length - 1) + pp(value); + }; + for (const key of keys || Object.keys(obj).sort()) { + const value = obj[key]; + if (Array.isArray(value)) { + if (value.length > 0) { + output.push(logKeyValue(key, value[0])); + for (const e of value.slice(1)) { + output.push(' '.repeat(maxKeyLength) + pp(e)); } } } - return args; - } - _debugOutput(args, flags, argv) { - if (argv.length > 0) { - debug('argv: %o', argv); - } - if (Object.keys(args).length > 0) { - debug('args: %o', args); - } - if (Object.keys(flags).length > 0) { - debug('flags: %o', flags); - } - } - _debugInput() { - debug('input: %s', this.argv.join(' ')); - if (this.input.args.length > 0) { - debug('available args: %s', this.input.args.map(a => a.name).join(' ')); + else if (value !== null && value !== undefined) { + output.push(logKeyValue(key, value)); } - if (Object.keys(this.input.flags).length === 0) - return; - debug('available flags: %s', Object.keys(this.input.flags) - .map(f => `--${f}`) - .join(' ')); - } - get _argTokens() { - return this.raw.filter(o => o.type === 'arg'); - } - get _flagTokens() { - return this.raw.filter(o => o.type === 'flag'); } - _setNames() { - for (const k of Object.keys(this.input.flags)) { - this.input.flags[k].name = k; - } + return output.join('\n'); +} +exports.Z = styledObject; + + +/***/ }), + +/***/ 14594: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ value: true }); +// 3pp +const cliProgress = __nccwpck_require__(17348); +function progress(options) { + // if no options passed, create empty options + if (!options) { + options = {}; } + // set noTTYOutput for options + options.noTTYOutput = Boolean(process.env.TERM === 'dumb' || !process.stdin.isTTY); + return new cliProgress.SingleBar(options); } -exports.Parser = Parser; +exports.Z = progress; /***/ }), -/***/ 30138: -/***/ ((__unused_webpack_module, exports) => { +/***/ 67729: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sortBy = exports.maxBy = exports.pickBy = void 0; -function pickBy(obj, fn) { - return Object.entries(obj) - .reduce((o, [k, v]) => { - if (fn(v)) - o[k] = v; - return o; - }, {}); -} -exports.pickBy = pickBy; -function maxBy(arr, fn) { - let max; - for (const cur of arr) { - const i = fn(cur); - if (!max || i > max.i) { - max = { i, element: cur }; - } +exports.table = void 0; +const F = __nccwpck_require__(78251); +const screen_1 = __nccwpck_require__(55463); +const chalk = __nccwpck_require__(1854); +const util_1 = __nccwpck_require__(40765); +const js_yaml_1 = __nccwpck_require__(21917); +const util_2 = __nccwpck_require__(73837); +const sw = __nccwpck_require__(42577); +const { orderBy } = __nccwpck_require__(56445); +class Table { + constructor(data, columns, options = {}) { + this.data = data; + // assign columns + this.columns = Object.keys(columns).map((key) => { + const col = columns[key]; + const extended = col.extended || false; + const get = col.get || ((row) => row[key]); + const header = typeof col.header === 'string' ? col.header : (0, util_1.capitalize)(key.replace(/_/g, ' ')); + const minWidth = Math.max(col.minWidth || 0, sw(header) + 1); + return { + extended, + get, + header, + key, + minWidth, + }; + }); + // assign options + const { columns: cols, filter, csv, output, extended, sort, title, printLine } = options; + this.options = { + columns: cols, + output: csv ? 'csv' : output, + extended, + filter, + 'no-header': options['no-header'] || false, + 'no-truncate': options['no-truncate'] || false, + printLine: printLine || ((s) => process.stdout.write(s + '\n')), + rowStart: ' ', + sort, + title, + }; } - return max && max.element; -} -exports.maxBy = maxBy; -function sortBy(arr, fn) { - // function castType(t: SortTypes | SortTypes[]): string | number | SortTypes[] { - // if (t === undefined) return 0 - // if (t === false) return 1 - // if (t === true) return -1 - // return t - // } - function compare(a, b) { - a = a === undefined ? 0 : a; - b = b === undefined ? 0 : b; - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length === 0 && b.length === 0) - return 0; - const diff = compare(a[0], b[0]); - if (diff !== 0) - return diff; - return compare(a.slice(1), b.slice(1)); + display() { + // build table rows from input array data + let rows = this.data.map(d => { + const row = {}; + for (const col of this.columns) { + let val = col.get(d); + if (typeof val !== 'string') + val = (0, util_2.inspect)(val, { breakLength: Number.POSITIVE_INFINITY }); + row[col.key] = val; + } + return row; + }); + // filter rows + if (this.options.filter) { + /* eslint-disable-next-line prefer-const */ + let [header, regex] = this.options.filter.split('='); + const isNot = header[0] === '-'; + if (isNot) + header = header.slice(1); + const col = this.findColumnFromHeader(header); + if (!col || !regex) + throw new Error('Filter flag has an invalid value'); + rows = rows.filter((d) => { + const re = new RegExp(regex); + const val = d[col.key]; + const match = val.match(re); + return isNot ? !match : match; + }); } - if (a < b) - return -1; - if (a > b) - return 1; - return 0; - } - return arr.sort((a, b) => compare(fn(a), fn(b))); -} -exports.sortBy = sortBy; - - -/***/ }), - -/***/ 99623: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; - -__webpack_unused_export__ = ({ value: true }); -exports.G = void 0; -const errors_1 = __nccwpck_require__(34630); -const errors_2 = __nccwpck_require__(27916); -function validate(parse) { - function validateArgs() { - const maxArgs = parse.input.args.length; - if (parse.input.strict && parse.output.argv.length > maxArgs) { - const extras = parse.output.argv.slice(maxArgs); - throw new errors_2.UnexpectedArgsError({ parse, args: extras }); + // sort rows + if (this.options.sort) { + const sorters = this.options.sort.split(','); + const sortHeaders = sorters.map(k => k[0] === '-' ? k.slice(1) : k); + const sortKeys = this.filterColumnsFromHeaders(sortHeaders).map(c => { + return ((v) => v[c.key]); + }); + const sortKeysOrder = sorters.map(k => k[0] === '-' ? 'desc' : 'asc'); + rows = orderBy(rows, sortKeys, sortKeysOrder); } - const missingRequiredArgs = []; - let hasOptional = false; - for (const [index, arg] of parse.input.args.entries()) { - if (!arg.required) { - hasOptional = true; - } - else if (hasOptional) { - // (required arg) check whether an optional has occurred before - // optionals should follow required, not before - throw new errors_2.InvalidArgsSpecError({ parse, args: parse.input.args }); - } - if (arg.required && !parse.output.argv[index] && parse.output.argv[index] !== 0) { - missingRequiredArgs.push(arg); - } + // and filter columns + if (this.options.columns) { + const filters = this.options.columns.split(','); + this.columns = this.filterColumnsFromHeaders(filters); } - if (missingRequiredArgs.length > 0) { - throw new errors_2.RequiredArgsError({ parse, args: missingRequiredArgs }); + else if (!this.options.extended) { + // show extented columns/properties + this.columns = this.columns.filter(c => !c.extended); + } + this.data = rows; + switch (this.options.output) { + case 'csv': + this.outputCSV(); + break; + case 'json': + this.outputJSON(); + break; + case 'yaml': + this.outputYAML(); + break; + default: + this.outputTable(); } } - function validateAcrossFlags(flag) { - const intersection = Object.entries(parse.input.flags) - .map(entry => entry[0]) // array of flag names - .filter(flagName => parse.output.flags[flagName] !== undefined) // with values - .filter(flagName => flag.exactlyOne && flag.exactlyOne.includes(flagName)); // and in the exactlyOne list - if (intersection.length === 0) { - // the command's exactlyOne may or may not include itself, so we'll use Set to add + de-dupe - throw new errors_1.CLIError(`Exactly one of the following must be provided: ${[ - ...new Set(...flag.exactlyOne || [], flag.name), - ].join(',')}`); + findColumnFromHeader(header) { + return this.columns.find(c => c.header.toLowerCase() === header.toLowerCase()); + } + filterColumnsFromHeaders(filters) { + // unique + filters = [...(new Set(filters))]; + const cols = []; + for (const f of filters) { + const c = this.columns.find(c => c.header.toLowerCase() === f.toLowerCase()); + if (c) + cols.push(c); } + return cols; } - function validateFlags() { - for (const [name, flag] of Object.entries(parse.input.flags)) { - if (parse.output.flags[name] !== undefined) { - for (const also of flag.dependsOn || []) { - if (!parse.output.flags[also]) { - throw new errors_1.CLIError(`--${also}= must also be provided when using --${name}=`); - } + getCSVRow(d) { + const values = this.columns.map(col => d[col.key] || ''); + const lineToBeEscaped = values.find((e) => e.includes('"') || e.includes('\n') || e.includes('\r\n') || e.includes('\r') || e.includes(',')); + return values.map(e => lineToBeEscaped ? `"${e.replace('"', '""')}"` : e); + } + resolveColumnsToObjectArray() { + // tslint:disable-next-line:no-this-assignment + const { data, columns } = this; + return data.map((d) => { + // eslint-disable-next-line unicorn/prefer-object-from-entries + return columns.reduce((obj, col) => { + return { + ...obj, + [col.key]: d[col.key] || '', + }; + }, {}); + }); + } + outputJSON() { + this.options.printLine(JSON.stringify(this.resolveColumnsToObjectArray(), undefined, 2)); + } + outputYAML() { + this.options.printLine((0, js_yaml_1.safeDump)(this.resolveColumnsToObjectArray())); + } + outputCSV() { + // tslint:disable-next-line:no-this-assignment + const { data, columns, options } = this; + if (!options['no-header']) { + options.printLine(columns.map(c => c.header).join(',')); + } + for (const d of data) { + const row = this.getCSVRow(d); + options.printLine(row.join(',')); + } + } + outputTable() { + // tslint:disable-next-line:no-this-assignment + const { data, columns, options } = this; + // column truncation + // + // find max width for each column + for (const col of columns) { + // convert multi-line cell to single longest line + // for width calculations + const widthData = data.map((row) => { + const d = row[col.key]; + const manyLines = d.split('\n'); + if (manyLines.length > 1) { + return '*'.repeat(Math.max(...manyLines.map((r) => sw(r)))); } - for (const also of flag.exclusive || []) { - // do not enforce exclusivity for flags that were defaulted - if (parse.output.metadata.flags[also] && - parse.output.metadata.flags[also].setFromDefault) - continue; - if (parse.output.metadata.flags[name] && - parse.output.metadata.flags[name].setFromDefault) - continue; - if (parse.output.flags[also]) { - throw new errors_1.CLIError(`--${also}= cannot also be provided when using --${name}=`); - } + return d; + }); + const widths = ['.'.padEnd(col.minWidth - 1), col.header, ...widthData.map((row) => row)].map(r => sw(r)); + col.maxWidth = Math.max(...widths) + 1; + col.width = col.maxWidth; + } + // terminal width + const maxWidth = screen_1.stdtermwidth - 2; + // truncation logic + const shouldShorten = () => { + // don't shorten if full mode + if (options['no-truncate'] || (!process.stdout.isTTY && !process.env.CLI_UX_SKIP_TTY_CHECK)) + return; + // don't shorten if there is enough screen width + const dataMaxWidth = (0, util_1.sumBy)(columns, c => c.width); + const overWidth = dataMaxWidth - maxWidth; + if (overWidth <= 0) + return; + // not enough room, short all columns to minWidth + for (const col of columns) { + col.width = col.minWidth; + } + // if sum(minWidth's) is greater than term width + // nothing can be done so + // display all as minWidth + const dataMinWidth = (0, util_1.sumBy)(columns, c => c.minWidth); + if (dataMinWidth >= maxWidth) + return; + // some wiggle room left, add it back to "needy" columns + let wiggleRoom = maxWidth - dataMinWidth; + const needyCols = columns.map(c => ({ key: c.key, needs: c.maxWidth - c.width })).sort((a, b) => a.needs - b.needs); + for (const { key, needs } of needyCols) { + if (!needs) + continue; + const col = columns.find(c => key === c.key); + if (!col) + continue; + if (wiggleRoom > needs) { + col.width = col.width + needs; + wiggleRoom -= needs; } - for (const also of flag.exactlyOne || []) { - if (also !== name && parse.output.flags[also]) { - throw new errors_1.CLIError(`--${also}= cannot also be provided when using --${name}=`); - } + else if (wiggleRoom) { + col.width = col.width + wiggleRoom; + wiggleRoom = 0; } } - else if (flag.required) { - throw new errors_2.RequiredFlagError({ parse, flag }); + }; + shouldShorten(); + // print table title + if (options.title) { + options.printLine(options.title); + // print title divider + options.printLine(''.padEnd(columns.reduce((sum, col) => sum + col.width, 1), '=')); + options.rowStart = '| '; + } + // print headers + if (!options['no-header']) { + let headers = options.rowStart; + for (const col of columns) { + const header = col.header; + headers += header.padEnd(col.width); } - else if (flag.exactlyOne && flag.exactlyOne.length > 0) { - validateAcrossFlags(flag); + options.printLine(chalk.bold(headers)); + // print header dividers + let dividers = options.rowStart; + for (const col of columns) { + const divider = ''.padEnd(col.width - 1, '─') + ' '; + dividers += divider.padEnd(col.width); + } + options.printLine(chalk.bold(dividers)); + } + // print rows + for (const row of data) { + // find max number of lines + // for all cells in a row + // with multi-line strings + let numOfLines = 1; + for (const col of columns) { + const d = row[col.key]; + const lines = d.split('\n').length; + if (lines > numOfLines) + numOfLines = lines; + } + // eslint-disable-next-line unicorn/no-new-array + const linesIndexess = [...new Array(numOfLines).keys()]; + // print row + // including multi-lines + for (const i of linesIndexess) { + let l = options.rowStart; + for (const col of columns) { + const width = col.width; + let d = row[col.key]; + d = d.split('\n')[i] || ''; + const visualWidth = sw(d); + const colorWidth = (d.length - visualWidth); + let cell = d.padEnd(width + colorWidth); + if ((cell.length - colorWidth) > width || visualWidth === width) { + cell = cell.slice(0, width - 2) + '… '; + } + l += cell; + } + options.printLine(l); } } } - validateArgs(); - validateFlags(); } -exports.G = validate; +function table(data, columns, options = {}) { + new Table(data, columns, options).display(); +} +exports.table = table; +(function (table) { + table.Flags = { + columns: F.string({ exclusive: ['extended'], description: 'only show provided columns (comma-separated)' }), + sort: F.string({ description: 'property to sort by (prepend \'-\' for descending)' }), + filter: F.string({ description: 'filter property by partial string matching, ex: name=foo' }), + csv: F.boolean({ exclusive: ['no-truncate'], description: 'output is csv format [alias: --output=csv]' }), + output: F.string({ + exclusive: ['no-truncate', 'csv'], + description: 'output in a more machine friendly format', + options: ['csv', 'json', 'yaml'], + }), + extended: F.boolean({ exclusive: ['columns'], char: 'x', description: 'show extra columns' }), + 'no-truncate': F.boolean({ exclusive: ['csv'], description: 'do not truncate output to fit screen' }), + 'no-header': F.boolean({ exclusive: ['csv'], description: 'hide table header from output' }), + }; + function flags(opts) { + if (opts) { + const f = {}; + const o = (opts.only && typeof opts.only === 'string' ? [opts.only] : opts.only) || Object.keys(table.Flags); + const e = (opts.except && typeof opts.except === 'string' ? [opts.except] : opts.except) || []; + for (const key of o) { + if (!e.includes(key)) { + f[key] = table.Flags[key]; + } + } + return f; + } + return table.Flags; + } + table.flags = flags; +})(table = exports.table || (exports.table = {})); /***/ }), -/***/ 12051: +/***/ 68363: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +var __webpack_unused_export__; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.errtermwidth = exports.stdtermwidth = void 0; -const settings_1 = __nccwpck_require__(86464); -function termwidth(stream) { - if (!stream.isTTY) { - return 80; +__webpack_unused_export__ = ({ value: true }); +__webpack_unused_export__ = void 0; +const treeify = __nccwpck_require__(87817); +class Tree { + constructor() { + this.nodes = {}; } - const width = stream.getWindowSize()[0]; - if (width < 1) { - return 80; + insert(child, value = new Tree()) { + this.nodes[child] = value; + return this; } - if (width < 40) { - return 40; + search(key) { + for (const child of Object.keys(this.nodes)) { + if (child === key) { + return this.nodes[child]; + } + const c = this.nodes[child].search(key); + if (c) + return c; + } + } + // tslint:disable-next-line:no-console + display(logger = console.log) { + const addNodes = function (nodes) { + const tree = {}; + for (const p of Object.keys(nodes)) { + tree[p] = addNodes(nodes[p].nodes); + } + return tree; + }; + const tree = addNodes(this.nodes); + logger(treeify(tree)); } - return width; } -const columns = Number.parseInt(process.env.OCLIF_COLUMNS, 10) || settings_1.settings.columns; -exports.stdtermwidth = columns || termwidth(process.stdout); -exports.errtermwidth = columns || termwidth(process.stderr); +__webpack_unused_export__ = Tree; +function tree() { + return new Tree(); +} +exports.ZP = tree; /***/ }), -/***/ 86464: +/***/ 48871: /***/ ((__unused_webpack_module, exports) => { "use strict"; +var __webpack_unused_export__; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.settings = void 0; -// Set global.oclif to the new object if it wasn't set before -if (!global.oclif) - global.oclif = {}; -exports.settings = global.oclif; +__webpack_unused_export__ = ({ value: true }); +// tslint:disable no-string-based-set-timeout +exports.Z = (ms = 1000) => { + return new Promise(resolve => { + setTimeout(resolve, ms); + }); +}; /***/ }), -/***/ 14169: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 85635: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; /* module decorator */ module = __nccwpck_require__.nmd(module); - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url_1 = __nccwpck_require__(57310); +const util_1 = __nccwpck_require__(73837); +const index_1 = __nccwpck_require__(64874); +const config_1 = __nccwpck_require__(13832); +const Errors = __nccwpck_require__(34630); +const Parser = __nccwpck_require__(44195); +const Flags = __nccwpck_require__(78251); +const pjson = __nccwpck_require__(56193); +/** + * swallows stdout epipe errors + * this occurs when stdout closes such as when piping to head + */ +process.stdout.on('error', (err) => { + if (err && err.code === 'EPIPE') + return; + throw err; +}); +const jsonFlag = { + json: Flags.boolean({ + description: 'Format output as json.', + helpGroup: 'GLOBAL', + }), }; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = __nccwpck_require__(64816); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; +/** + * An abstract class which acts as the base for each command + * in your project. + */ +class Command { + constructor(argv, config) { + this.argv = argv; + this.config = config; + this.id = this.ctor.id; + try { + this.debug = __nccwpck_require__(38237)(this.id ? `${this.config.bin}:${this.id}` : this.config.bin); + } + catch { + this.debug = () => { }; + } + } + static get globalFlags() { + return this._globalFlags; + } + static set globalFlags(flags) { + this._globalFlags = this.enableJsonFlag ? + Object.assign({}, jsonFlag, this.globalFlags, flags) : + Object.assign({}, this.globalFlags, flags); + } + static get flags() { + return this._flags; + } + static set flags(flags) { + this.globalFlags = {}; + this._flags = Object.assign({}, this.globalFlags, flags); + } + get ctor() { + return this.constructor; + } + async _run() { + let err; + let result; + try { + // remove redirected env var to allow subsessions to run autoupdated client + delete process.env[this.config.scopedEnvVarKey('REDIRECTED')]; + await this.init(); + result = await this.run(); + } + catch (error) { + err = error; + await this.catch(error); + } + finally { + await this.finally(err); + } + if (result && this.jsonEnabled()) { + index_1.CliUx.ux.styledJSON(this.toSuccessJson(result)); + } + return result; + } + exit(code = 0) { + return Errors.exit(code); + } + warn(input) { + if (!this.jsonEnabled()) + Errors.warn(input); + return input; + } + error(input, options = {}) { + return Errors.error(input, options); + } + log(message = '', ...args) { + if (!this.jsonEnabled()) { + // tslint:disable-next-line strict-type-predicates + message = typeof message === 'string' ? message : (0, util_1.inspect)(message); + process.stdout.write((0, util_1.format)(message, ...args) + '\n'); + } + } + jsonEnabled() { + return this.ctor.enableJsonFlag && this.argv.includes('--json'); + } + async init() { + this.debug('init version: %s argv: %o', this.ctor._base, this.argv); + if (this.config.debug) + Errors.config.debug = true; + if (this.config.errlog) + Errors.config.errlog = this.config.errlog; + // global['cli-ux'].context = global['cli-ux'].context || { + // command: compact([this.id, ...this.argv]).join(' '), + // version: this.config.userAgent, + // } + const g = global; + g['http-call'] = g['http-call'] || {}; + g['http-call'].userAgent = this.config.userAgent; + } + async parse(options, argv = this.argv) { + if (!options) + options = this.constructor; + const opts = { context: this, ...options }; + // the spread operator doesn't work with getters so we have to manually add it here + opts.flags = options === null || options === void 0 ? void 0 : options.flags; + return Parser.parse(argv, opts); + } + async catch(err) { + var _a, _b; + process.exitCode = (_b = (_a = process.exitCode) !== null && _a !== void 0 ? _a : err.exitCode) !== null && _b !== void 0 ? _b : 1; + if (this.jsonEnabled()) { + index_1.CliUx.ux.styledJSON(this.toErrorJson(err)); + } + else { + if (!err.message) + throw err; + try { + const chalk = __nccwpck_require__(1854); + index_1.CliUx.ux.action.stop(chalk.bold.red('!')); + } + catch { } + throw err; + } + } + async finally(_) { + try { + const config = Errors.config; + if (config.errorLogger) + await config.errorLogger.flush(); + // tslint:disable-next-line no-console + } + catch (error) { + console.error(error); + } + } + toSuccessJson(result) { + return result; + } + toErrorJson(err) { + return { error: err }; + } } - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +exports["default"] = Command; +Command._base = `${pjson.name}@${pjson.version}`; +/** An array of aliases for this command. */ +Command.aliases = []; +/** When set to false, allows a variable amount of arguments */ +Command.strict = true; +Command.parse = true; +Command.parserOptions = {}; +Command.enableJsonFlag = false; +// eslint-disable-next-line valid-jsdoc +/** + * instantiate and run the command + * @param {Interfaces.Command.Class} this Class + * @param {string[]} argv argv + * @param {Interfaces.LoadOptions} opts options + */ +Command.run = async function (argv, opts) { + if (!argv) + argv = process.argv.slice(2); + // Handle the case when a file URL string is passed in such as 'import.meta.url'; covert to file path. + if (typeof opts === 'string' && opts.startsWith('file://')) { + opts = (0, url_1.fileURLToPath)(opts); + } + // to-do: update in node-14 to module.main + const config = await config_1.Config.load(opts || (module.parent && module.parent.parent && module.parent.parent.filename) || __dirname); + const cmd = new this(argv, config); + return cmd._run(argv); +}; /***/ }), -/***/ 1854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 65436: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; +/* module decorator */ module = __nccwpck_require__.nmd(module); -const ansiStyles = __nccwpck_require__(14169); -const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(62901); -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = __nccwpck_require__(76024); - -const {isArray} = Array; - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; - -const styles = Object.create(null); - -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } - - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; - -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} - -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; - - chalk.template.Instance = ChalkClass; - - return chalk.template; -}; - -function Chalk(options) { - return chalkFactory(options); -} - -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCached = exports.Config = void 0; +const errors_1 = __nccwpck_require__(34630); +const ejs = __nccwpck_require__(58431); +const os = __nccwpck_require__(22037); +const path = __nccwpck_require__(71017); +const url_1 = __nccwpck_require__(57310); +const util_1 = __nccwpck_require__(73837); +const Plugin = __nccwpck_require__(35331); +const util_2 = __nccwpck_require__(38008); +const util_3 = __nccwpck_require__(40765); +const module_loader_1 = __nccwpck_require__(87445); +const util_4 = __nccwpck_require__(67934); +// eslint-disable-next-line new-cap +const debug = (0, util_2.Debug)(); +const _pjson = __nccwpck_require__(56193); +function channelFromVersion(version) { + const m = version.match(/[^-]+(?:-([^.]+))?/); + return (m && m[1]) || 'stable'; } - -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; - -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; +const WSL = __nccwpck_require__(52559); +function isConfig(o) { + return o && Boolean(o._base); } - -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; +class Permutations extends Map { + constructor() { + super(...arguments); + this.validPermutations = new Map(); + } + add(permutation, commandId) { + this.validPermutations.set(permutation, commandId); + for (const id of (0, util_2.collectUsableIds)([permutation])) { + if (this.has(id)) { + this.set(id, this.get(id).add(commandId)); + } + else { + this.set(id, new Set([commandId])); + } + } + } + get(key) { + var _a; + return (_a = super.get(key)) !== null && _a !== void 0 ? _a : new Set(); + } + getValid(key) { + return this.validPermutations.get(key); + } + getAllValid() { + return [...this.validPermutations.keys()]; + } + hasValid(key) { + return this.validPermutations.has(key); + } } - -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); - -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } - - return { - open, - close, - openAll, - closeAll, - parent - }; -}; - -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } - - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; - - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); - - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; - - return builder; -}; - -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } - - let styler = self._styler; - - if (styler === undefined) { - return string; - } - - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); - - styler = styler.parent; - } - } - - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } - - return openAll + string + closeAll; -}; - -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; - - if (!isArray(firstString) || !isArray(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); - } - - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; - - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } - - if (template === undefined) { - template = __nccwpck_require__(20744); - } - - return template(chalk, parts.join('')); -}; - -Object.defineProperties(Chalk.prototype, styles); - -const chalk = Chalk(); // eslint-disable-line new-cap -chalk.supportsColor = stdoutColor; -chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk.stderr.supportsColor = stderrColor; - -module.exports = chalk; - - -/***/ }), - -/***/ 20744: -/***/ ((module) => { - -"use strict"; - -const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; - - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } - - return ESCAPES.get(c) || c; -} - -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; - - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } - - return results; +class Config { + // eslint-disable-next-line no-useless-constructor + constructor(options) { + this.options = options; + this._base = `${_pjson.name}@${_pjson.version}`; + this.debug = 0; + this.plugins = []; + this.topicSeparator = ':'; + this.warned = false; + this.commandPermutations = new Permutations(); + this.topicPermutations = new Permutations(); + this._commands = new Map(); + this._topics = new Map(); + } + static async load(opts = (module.parent && module.parent.parent && module.parent.parent.filename) || __dirname) { + // Handle the case when a file URL string is passed in such as 'import.meta.url'; covert to file path. + if (typeof opts === 'string' && opts.startsWith('file://')) { + opts = (0, url_1.fileURLToPath)(opts); + } + if (typeof opts === 'string') + opts = { root: opts }; + if (isConfig(opts)) + return opts; + const config = new Config(opts); + await config.load(); + return config; + } + // eslint-disable-next-line complexity + async load() { + const plugin = new Plugin.Plugin({ root: this.options.root }); + await plugin.load(); + this.plugins.push(plugin); + this.root = plugin.root; + this.pjson = plugin.pjson; + this.name = this.pjson.name; + this.version = this.options.version || this.pjson.version || '0.0.0'; + this.channel = this.options.channel || channelFromVersion(this.version); + this.valid = plugin.valid; + this.arch = (os.arch() === 'ia32' ? 'x86' : os.arch()); + this.platform = WSL ? 'wsl' : os.platform(); + this.windows = this.platform === 'win32'; + this.bin = this.pjson.oclif.bin || this.name; + this.dirname = this.pjson.oclif.dirname || this.name; + this.flexibleTaxonomy = this.pjson.oclif.flexibleTaxonomy || false; + // currently, only colons or spaces are valid separators + if (this.pjson.oclif.topicSeparator && [':', ' '].includes(this.pjson.oclif.topicSeparator)) + this.topicSeparator = this.pjson.oclif.topicSeparator; + if (this.platform === 'win32') + this.dirname = this.dirname.replace('/', '\\'); + this.userAgent = `${this.name}/${this.version} ${this.platform}-${this.arch} node-${process.version}`; + this.shell = this._shell(); + this.debug = this._debug(); + this.home = process.env.HOME || (this.windows && this.windowsHome()) || os.homedir() || os.tmpdir(); + this.cacheDir = this.scopedEnvVar('CACHE_DIR') || this.macosCacheDir() || this.dir('cache'); + this.configDir = this.scopedEnvVar('CONFIG_DIR') || this.dir('config'); + this.dataDir = this.scopedEnvVar('DATA_DIR') || this.dir('data'); + this.errlog = path.join(this.cacheDir, 'error.log'); + this.binPath = this.scopedEnvVar('BINPATH'); + this.npmRegistry = this.scopedEnvVar('NPM_REGISTRY') || this.pjson.oclif.npmRegistry; + this.pjson.oclif.update = this.pjson.oclif.update || {}; + this.pjson.oclif.update.node = this.pjson.oclif.update.node || {}; + const s3 = this.pjson.oclif.update.s3 || {}; + this.pjson.oclif.update.s3 = s3; + s3.bucket = this.scopedEnvVar('S3_BUCKET') || s3.bucket; + if (s3.bucket && !s3.host) + s3.host = `https://${s3.bucket}.s3.amazonaws.com`; + s3.templates = { + ...s3.templates, + target: { + baseDir: '<%- bin %>', + unversioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %>-<%- platform %>-<%- arch %><%- ext %>", + versioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %>-v<%- version %>/<%- bin %>-v<%- version %>-<%- platform %>-<%- arch %><%- ext %>", + manifest: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- platform %>-<%- arch %>", + ...s3.templates && s3.templates.target, + }, + vanilla: { + unversioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %><%- ext %>", + versioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %>-v<%- version %>/<%- bin %>-v<%- version %><%- ext %>", + baseDir: '<%- bin %>', + manifest: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %>version", + ...s3.templates && s3.templates.vanilla, + }, + }; + await this.loadUserPlugins(); + await this.loadDevPlugins(); + await this.loadCorePlugins(); + for (const plugin of this.plugins) { + this.loadCommands(plugin); + this.loadTopics(plugin); + } + debug('config done'); + } + async loadCorePlugins() { + if (this.pjson.oclif.plugins) { + await this.loadPlugins(this.root, 'core', this.pjson.oclif.plugins); + } + } + async loadDevPlugins() { + // do not load oclif.devPlugins in production + if (this.isProd) + return; + try { + const devPlugins = this.pjson.oclif.devPlugins; + if (devPlugins) + await this.loadPlugins(this.root, 'dev', devPlugins); + } + catch (error) { + process.emitWarning(error); + } + } + async loadUserPlugins() { + if (this.options.userPlugins !== false) { + try { + const userPJSONPath = path.join(this.dataDir, 'package.json'); + debug('reading user plugins pjson %s', userPJSONPath); + const pjson = await (0, util_2.loadJSON)(userPJSONPath); + this.userPJSON = pjson; + if (!pjson.oclif) + pjson.oclif = { schema: 1 }; + if (!pjson.oclif.plugins) + pjson.oclif.plugins = []; + await this.loadPlugins(userPJSONPath, 'user', pjson.oclif.plugins.filter((p) => p.type === 'user')); + await this.loadPlugins(userPJSONPath, 'link', pjson.oclif.plugins.filter((p) => p.type === 'link')); + } + catch (error) { + if (error.code !== 'ENOENT') + process.emitWarning(error); + } + } + } + async runHook(event, opts, timeout) { + debug('start %s hook', event); + const search = (m) => { + if (typeof m === 'function') + return m; + if (m.default && typeof m.default === 'function') + return m.default; + return Object.values(m).find((m) => typeof m === 'function'); + }; + const withTimeout = async (ms, promise) => { + let id; + const timeout = new Promise((_, reject) => { + id = setTimeout(() => { + reject(new Error(`Timed out after ${ms} ms.`)); + }, ms).unref(); + }); + return Promise.race([promise, timeout]).then(result => { + clearTimeout(id); + return result; + }); + }; + const final = { + successes: [], + failures: [], + }; + const promises = this.plugins.map(async (p) => { + const debug = __nccwpck_require__(38237)([this.bin, p.name, 'hooks', event].join(':')); + const context = { + config: this, + debug, + exit(code = 0) { + (0, errors_1.exit)(code); + }, + log(message, ...args) { + process.stdout.write((0, util_1.format)(message, ...args) + '\n'); + }, + error(message, options = {}) { + (0, errors_1.error)(message, options); + }, + warn(message) { + (0, errors_1.warn)(message); + }, + }; + const hooks = p.hooks[event] || []; + for (const hook of hooks) { + try { + /* eslint-disable no-await-in-loop */ + const { isESM, module, filePath } = await module_loader_1.default.loadWithData(p, hook); + debug('start', isESM ? '(import)' : '(require)', filePath); + const result = timeout ? + await withTimeout(timeout, search(module).call(context, { ...opts, config: this })) : + await search(module).call(context, { ...opts, config: this }); + final.successes.push({ plugin: p, result }); + debug('done'); + } + catch (error) { + final.failures.push({ plugin: p, error: error }); + debug(error); + } + } + }); + await Promise.all(promises); + debug('%s hook done', event); + return final; + } + // eslint-disable-next-line default-param-last + async runCommand(id, argv = [], cachedCommand) { + debug('runCommand %s %o', id, argv); + const c = cachedCommand || this.findCommand(id); + if (!c) { + const matches = this.flexibleTaxonomy ? this.findMatches(id, argv) : []; + const hookResult = this.flexibleTaxonomy && matches.length > 0 ? + await this.runHook('command_incomplete', { id, argv, matches }) : + await this.runHook('command_not_found', { id, argv }); + if (hookResult.successes[0]) { + const cmdResult = hookResult.successes[0].result; + return cmdResult; + } + throw new errors_1.CLIError(`command ${id} not found`); + } + const command = await c.load(); + await this.runHook('prerun', { Command: command, argv }); + const result = (await command.run(argv, this)); + await this.runHook('postrun', { Command: command, result: result, argv }); + return result; + } + scopedEnvVar(k) { + return process.env[this.scopedEnvVarKey(k)]; + } + scopedEnvVarTrue(k) { + const v = process.env[this.scopedEnvVarKey(k)]; + return v === '1' || v === 'true'; + } + scopedEnvVarKey(k) { + return [this.bin, k] + .map(p => p.replace(/@/g, '').replace(/[/-]/g, '_')) + .join('_') + .toUpperCase(); + } + findCommand(id, opts = {}) { + const lookupId = this.getCmdLookupId(id); + const command = this._commands.get(lookupId); + if (opts.must && !command) + (0, errors_1.error)(`command ${lookupId} not found`); + return command; + } + findTopic(name, opts = {}) { + const lookupId = this.getTopicLookupId(name); + const topic = this._topics.get(lookupId); + if (topic) + return topic; + if (opts.must) + throw new Error(`topic ${name} not found`); + } + /** + * Find all command ids that include the provided command id. + * + * For example, if the command ids are: + * - foo:bar:baz + * - one:two:three + * + * `bar` would return `foo:bar:baz` + * + * @param partialCmdId string + * @param argv string[] process.argv containing the flags and arguments provided by the user + * @returns string[] + */ + findMatches(partialCmdId, argv) { + const flags = argv.filter(arg => !(0, util_4.getHelpFlagAdditions)(this).includes(arg) && arg.startsWith('-')).map(a => a.replace(/-/g, '')); + const possibleMatches = [...this.commandPermutations.get(partialCmdId)].map(k => this._commands.get(k)); + const matches = possibleMatches.filter(command => { + const cmdFlags = Object.entries(command.flags).flatMap(([flag, def]) => { + return def.char ? [def.char, flag] : [flag]; + }); + // A command is a match if the provided flags belong to the full command + return flags.every(f => cmdFlags.includes(f)); + }); + return matches; + } + /** + * Returns an array of all commands. If flexible taxonomy is enabled then all permutations will be appended to the array. + * @returns Command.Loadable[] + */ + getAllCommands() { + const commands = [...this._commands.values()]; + const validPermutations = [...this.commandPermutations.getAllValid()]; + for (const permutation of validPermutations) { + if (!this._commands.has(permutation)) { + const cmd = this._commands.get(this.getCmdLookupId(permutation)); + commands.push({ ...cmd, id: permutation }); + } + } + return commands; + } + /** + * Returns an array of all command ids. If flexible taxonomy is enabled then all permutations will be appended to the array. + * @returns string[] + */ + getAllCommandIDs() { + return this.getAllCommands().map(c => c.id); + } + get commands() { + return [...this._commands.values()]; + } + get commandIDs() { + if (this._commandIDs) + return this._commandIDs; + this._commandIDs = this.commands.map(c => c.id); + return this._commandIDs; + } + get topics() { + return [...this._topics.values()]; + } + s3Key(type, ext, options = {}) { + var _a; + if (typeof ext === 'object') + options = ext; + else if (ext) + options.ext = ext; + const template = (_a = this.pjson.oclif.update.s3.templates[options.platform ? 'target' : 'vanilla'][type]) !== null && _a !== void 0 ? _a : ''; + return ejs.render(template, { ...this, ...options }); + } + s3Url(key) { + const host = this.pjson.oclif.update.s3.host; + if (!host) + throw new Error('no s3 host is set'); + const url = new url_1.URL(host); + url.pathname = path.join(url.pathname, key); + return url.toString(); + } + dir(category) { + const base = process.env[`XDG_${category.toUpperCase()}_HOME`] || + (this.windows && process.env.LOCALAPPDATA) || + path.join(this.home, category === 'data' ? '.local/share' : '.' + category); + return path.join(base, this.dirname); + } + windowsHome() { + return this.windowsHomedriveHome() || this.windowsUserprofileHome(); + } + windowsHomedriveHome() { + return (process.env.HOMEDRIVE && process.env.HOMEPATH && path.join(process.env.HOMEDRIVE, process.env.HOMEPATH)); + } + windowsUserprofileHome() { + return process.env.USERPROFILE; + } + macosCacheDir() { + return (this.platform === 'darwin' && path.join(this.home, 'Library', 'Caches', this.dirname)) || undefined; + } + _shell() { + let shellPath; + const { SHELL, COMSPEC } = process.env; + if (SHELL) { + shellPath = SHELL.split('/'); + } + else if (this.windows && COMSPEC) { + shellPath = COMSPEC.split(/\\|\//); + } + else { + shellPath = ['unknown']; + } + return shellPath[shellPath.length - 1]; + } + _debug() { + if (this.scopedEnvVarTrue('DEBUG')) + return 1; + try { + const { enabled } = __nccwpck_require__(38237)(this.bin); + if (enabled) + return 1; + } + catch { } + return 0; + } + async loadPlugins(root, type, plugins, parent) { + if (!plugins || plugins.length === 0) + return; + debug('loading plugins', plugins); + await Promise.all((plugins || []).map(async (plugin) => { + try { + const opts = { type, root }; + if (typeof plugin === 'string') { + opts.name = plugin; + } + else { + opts.name = plugin.name || opts.name; + opts.tag = plugin.tag || opts.tag; + opts.root = plugin.root || opts.root; + } + const instance = new Plugin.Plugin(opts); + await instance.load(); + if (this.plugins.find(p => p.name === instance.name)) + return; + this.plugins.push(instance); + if (parent) { + instance.parent = parent; + if (!parent.children) + parent.children = []; + parent.children.push(instance); + } + await this.loadPlugins(instance.root, type, instance.pjson.oclif.plugins || [], instance); + } + catch (error) { + this.warn(error, 'loadPlugins'); + } + })); + } + warn(err, scope) { + if (this.warned) + return; + if (typeof err === 'string') { + process.emitWarning(err); + return; + } + if (err instanceof Error) { + const modifiedErr = err; + modifiedErr.name = `${err.name} Plugin: ${this.name}`; + modifiedErr.detail = (0, util_2.compact)([ + err.detail, + `module: ${this._base}`, + scope && `task: ${scope}`, + `plugin: ${this.name}`, + `root: ${this.root}`, + 'See more details with DEBUG=*', + ]).join('\n'); + process.emitWarning(err); + return; + } + // err is an object + process.emitWarning('Config.warn expected either a string or Error, but instead received an object'); + err.name = `${err.name} Plugin: ${this.name}`; + err.detail = (0, util_2.compact)([ + err.detail, + `module: ${this._base}`, + scope && `task: ${scope}`, + `plugin: ${this.name}`, + `root: ${this.root}`, + 'See more details with DEBUG=*', + ]).join('\n'); + process.emitWarning(JSON.stringify(err)); + } + get isProd() { + return (0, util_3.isProd)(); + } + getCmdLookupId(id) { + if (this._commands.has(id)) + return id; + if (this.commandPermutations.hasValid(id)) + return this.commandPermutations.getValid(id); + return id; + } + getTopicLookupId(id) { + if (this._topics.has(id)) + return id; + if (this.topicPermutations.hasValid(id)) + return this.topicPermutations.getValid(id); + return id; + } + loadCommands(plugin) { + var _a; + for (const command of plugin.commands) { + if (this._commands.has(command.id)) { + const prioritizedCommand = this.determinePriority([this._commands.get(command.id), command]); + this._commands.set(prioritizedCommand.id, prioritizedCommand); + } + else { + this._commands.set(command.id, command); + } + const permutations = this.flexibleTaxonomy ? (0, util_2.getCommandIdPermutations)(command.id) : [command.id]; + for (const permutation of permutations) { + this.commandPermutations.add(permutation, command.id); + } + for (const alias of (_a = command.aliases) !== null && _a !== void 0 ? _a : []) { + if (this._commands.has(alias)) { + const prioritizedCommand = this.determinePriority([this._commands.get(alias), command]); + this._commands.set(prioritizedCommand.id, { ...prioritizedCommand, id: alias }); + } + else { + this._commands.set(alias, { ...command, id: alias }); + } + const aliasPermutations = this.flexibleTaxonomy ? (0, util_2.getCommandIdPermutations)(alias) : [alias]; + for (const permutation of aliasPermutations) { + this.commandPermutations.add(permutation, command.id); + } + } + } + } + loadTopics(plugin) { + for (const topic of (0, util_2.compact)(plugin.topics)) { + const existing = this._topics.get(topic.name); + if (existing) { + existing.description = topic.description || existing.description; + existing.hidden = existing.hidden || topic.hidden; + } + else { + this._topics.set(topic.name, topic); + } + const permutations = this.flexibleTaxonomy ? (0, util_2.getCommandIdPermutations)(topic.name) : [topic.name]; + for (const permutation of permutations) { + this.topicPermutations.add(permutation, topic.name); + } + } + // Add missing topics for displaying help when partial commands are entered. + for (const c of plugin.commands.filter(c => !c.hidden)) { + const parts = c.id.split(':'); + while (parts.length > 0) { + const name = parts.join(':'); + if (name && !this._topics.has(name)) { + this._topics.set(name, { name, description: c.summary || c.description }); + } + parts.pop(); + } + } + } + /** + * This method is responsible for locating the correct plugin to use for a named command id + * It searches the {Config} registered commands to match either the raw command id or the command alias + * It is possible that more than one command will be found. This is due the ability of two distinct plugins to + * create the same command or command alias. + * + * In the case of more than one found command, the function will select the command based on the order in which + * the plugin is included in the package.json `oclif.plugins` list. The command that occurs first in the list + * is selected as the command to run. + * + * Commands can also be present from either an install or a link. When a command is one of these and a core plugin + * is present, this function defers to the core plugin. + * + * If there is not a core plugin command present, this function will return the first + * plugin as discovered (will not change the order) + * + * @param commands commands to determine the priority of + * @returns command instance {Command.Loadable} or undefined + */ + determinePriority(commands) { + var _a, _b; + const oclifPlugins = (_b = (_a = this.pjson.oclif) === null || _a === void 0 ? void 0 : _a.plugins) !== null && _b !== void 0 ? _b : []; + const commandPlugins = commands.sort((a, b) => { + var _a, _b; + const pluginAliasA = (_a = a.pluginAlias) !== null && _a !== void 0 ? _a : 'A-Cannot-Find-This'; + const pluginAliasB = (_b = b.pluginAlias) !== null && _b !== void 0 ? _b : 'B-Cannot-Find-This'; + const aIndex = oclifPlugins.indexOf(pluginAliasA); + const bIndex = oclifPlugins.indexOf(pluginAliasB); + // When both plugin types are 'core' plugins sort based on index + if (a.pluginType === 'core' && b.pluginType === 'core') { + // If b appears first in the pjson.plugins sort it first + return aIndex - bIndex; + } + // if b is a core plugin and a is not sort b first + if (b.pluginType === 'core' && a.pluginType !== 'core') { + return 1; + } + // if a is a core plugin and b is not sort a first + if (a.pluginType === 'core' && b.pluginType !== 'core') { + return -1; + } + // neither plugin is core, so do not change the order + return 0; + }); + return commandPlugins[0]; + } } - -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; +exports.Config = Config; +// when no manifest exists, the default is calculated. This may throw, so we need to catch it +const defaultToCached = async (flag) => { + // Prefer the helpDefaultValue function (returns a friendly string for complex types) + if (typeof flag.defaultHelp === 'function') { + try { + return await flag.defaultHelp(); + } + catch { + return; + } + } + // if not specified, try the default function + if (typeof flag.default === 'function') { + try { + return await flag.default({ options: {}, flags: {} }); + } + catch { } + } + else { + return flag.default; + } +}; +async function toCached(c, plugin) { + const flags = {}; + for (const [name, flag] of Object.entries(c.flags || {})) { + if (flag.type === 'boolean') { + flags[name] = { + name, + type: flag.type, + char: flag.char, + summary: flag.summary, + description: flag.description, + hidden: flag.hidden, + required: flag.required, + helpLabel: flag.helpLabel, + helpGroup: flag.helpGroup, + allowNo: flag.allowNo, + dependsOn: flag.dependsOn, + exclusive: flag.exclusive, + }; + } + else { + flags[name] = { + name, + type: flag.type, + char: flag.char, + summary: flag.summary, + description: flag.description, + hidden: flag.hidden, + required: flag.required, + helpLabel: flag.helpLabel, + helpValue: flag.helpValue, + helpGroup: flag.helpGroup, + multiple: flag.multiple, + options: flag.options, + dependsOn: flag.dependsOn, + exclusive: flag.exclusive, + default: await defaultToCached(flag), + }; + // a command-level placeholder in the manifest so that oclif knows it should regenerate the command during help-time + if (typeof flag.defaultHelp === 'function') { + c.hasDynamicHelp = true; + } + } + } + const argsPromise = (c.args || []).map(async (a) => ({ + name: a.name, + description: a.description, + required: a.required, + options: a.options, + default: typeof a.default === 'function' ? await a.default({}) : a.default, + hidden: a.hidden, + })); + const args = await Promise.all(argsPromise); + const stdProperties = { + id: c.id, + summary: c.summary, + description: c.description, + strict: c.strict, + usage: c.usage, + pluginName: plugin && plugin.name, + pluginAlias: plugin && plugin.alias, + pluginType: plugin && plugin.type, + hidden: c.hidden, + state: c.state, + aliases: c.aliases || [], + examples: c.examples || c.example, + flags, + args, + }; + // do not include these properties in manifest + const ignoreCommandProperties = ['plugin', '_flags']; + const stdKeys = Object.keys(stdProperties); + const keysToAdd = Object.keys(c).filter(property => ![...stdKeys, ...ignoreCommandProperties].includes(property)); + const additionalProperties = {}; + for (const key of keysToAdd) { + additionalProperties[key] = c[key]; + } + return { ...stdProperties, ...additionalProperties }; } +exports.toCached = toCached; -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } +/***/ }), - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } +/***/ 13832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } +"use strict"; - return current; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.tsPath = exports.Plugin = exports.toCached = exports.Config = void 0; +try { + // eslint-disable-next-line node/no-missing-require + __nccwpck_require__(8387); } - -module.exports = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); - - chunks.push(chunk.join('')); - - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } - - return chunks.join(''); -}; +catch { } +var config_1 = __nccwpck_require__(65436); +Object.defineProperty(exports, "Config", ({ enumerable: true, get: function () { return config_1.Config; } })); +Object.defineProperty(exports, "toCached", ({ enumerable: true, get: function () { return config_1.toCached; } })); +var plugin_1 = __nccwpck_require__(35331); +Object.defineProperty(exports, "Plugin", ({ enumerable: true, get: function () { return plugin_1.Plugin; } })); +var ts_node_1 = __nccwpck_require__(3692); +Object.defineProperty(exports, "tsPath", ({ enumerable: true, get: function () { return ts_node_1.tsPath; } })); /***/ }), -/***/ 76024: -/***/ ((module) => { +/***/ 35331: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } - - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Plugin = void 0; +const errors_1 = __nccwpck_require__(34630); +const path = __nccwpck_require__(71017); +const util_1 = __nccwpck_require__(73837); +const config_1 = __nccwpck_require__(65436); +const util_2 = __nccwpck_require__(38008); +const ts_node_1 = __nccwpck_require__(3692); +const util_3 = __nccwpck_require__(38008); +const util_4 = __nccwpck_require__(40765); +const module_loader_1 = __nccwpck_require__(87445); +const _pjson = __nccwpck_require__(56193); +function topicsToArray(input, base) { + if (!input) + return []; + base = base ? `${base}:` : ''; + if (Array.isArray(input)) { + return input.concat((0, util_3.flatMap)(input, t => topicsToArray(t.subtopics, `${base}${t.name}`))); + } + return (0, util_3.flatMap)(Object.keys(input), k => { + input[k].name = k; + return [{ ...input[k], name: `${base}${k}` }].concat(topicsToArray(input[k].subtopics, `${base}${input[k].name}`)); + }); +} +// essentially just "cd .." +function* up(from) { + while (path.dirname(from) !== from) { + yield from; + from = path.dirname(from); + } + yield from; +} +async function findSourcesRoot(root) { + for (const next of up(root)) { + const cur = path.join(next, 'package.json'); + // eslint-disable-next-line no-await-in-loop + if (await (0, util_3.exists)(cur)) + return path.dirname(cur); + } +} +/** + * @returns string + * @param name string + * @param root string + * find package root + * for packages installed into node_modules this will go up directories until + * it finds a node_modules directory with the plugin installed into it + * + * This is needed because some oclif plugins do not declare the `main` field in their package.json + * https://github.com/oclif/config/pull/289#issuecomment-983904051 + */ +async function findRootLegacy(name, root) { + for (const next of up(root)) { + let cur; + if (name) { + cur = path.join(next, 'node_modules', name, 'package.json'); + // eslint-disable-next-line no-await-in-loop + if (await (0, util_3.exists)(cur)) + return path.dirname(cur); + try { + // eslint-disable-next-line no-await-in-loop + const pkg = await (0, util_3.loadJSON)(path.join(next, 'package.json')); + if (pkg.name === name) + return next; + } + catch { } + } + else { + cur = path.join(next, 'package.json'); + // eslint-disable-next-line no-await-in-loop + if (await (0, util_3.exists)(cur)) + return path.dirname(cur); + } + } +} +async function findRoot(name, root) { + if (name) { + let pkgPath; + try { + pkgPath = (0, util_3.resolvePackage)(name, { paths: [root] }); + } + catch { } + return pkgPath ? findSourcesRoot(path.dirname(pkgPath)) : findRootLegacy(name, root); + } + return findSourcesRoot(root); +} +class Plugin { + // eslint-disable-next-line no-useless-constructor + constructor(options) { + this.options = options; + // static loadedPlugins: {[name: string]: Plugin} = {} + this._base = `${_pjson.name}@${_pjson.version}`; + this.valid = false; + this.alreadyLoaded = false; + this.children = []; + // eslint-disable-next-line new-cap + this._debug = (0, util_2.Debug)(); + this.warned = false; + } + async load() { + var _a; + this.type = this.options.type || 'core'; + this.tag = this.options.tag; + const root = await findRoot(this.options.name, this.options.root); + if (!root) + throw new Error(`could not find package.json with ${(0, util_1.inspect)(this.options)}`); + this.root = root; + this._debug('reading %s plugin %s', this.type, root); + this.pjson = await (0, util_3.loadJSON)(path.join(root, 'package.json')); + this.name = this.pjson.name; + this.alias = (_a = this.options.name) !== null && _a !== void 0 ? _a : this.pjson.name; + const pjsonPath = path.join(root, 'package.json'); + if (!this.name) + throw new Error(`no name in ${pjsonPath}`); + if (!(0, util_4.isProd)() && !this.pjson.files) + this.warn(`files attribute must be specified in ${pjsonPath}`); + // eslint-disable-next-line new-cap + this._debug = (0, util_2.Debug)(this.name); + this.version = this.pjson.version; + if (this.pjson.oclif) { + this.valid = true; + } + else { + this.pjson.oclif = this.pjson['cli-engine'] || {}; + } + this.hooks = (0, util_3.mapValues)(this.pjson.oclif.hooks || {}, i => Array.isArray(i) ? i : [i]); + this.manifest = await this._manifest(Boolean(this.options.ignoreManifest), Boolean(this.options.errorOnManifestCreate)); + this.commands = Object + .entries(this.manifest.commands) + .map(([id, c]) => ({ ...c, pluginAlias: this.alias, pluginType: this.type, load: async () => this.findCommand(id, { must: true }) })) + .sort((a, b) => a.id.localeCompare(b.id)); + } + get topics() { + return topicsToArray(this.pjson.oclif.topics || {}); + } + get commandsDir() { + return (0, ts_node_1.tsPath)(this.root, this.pjson.oclif.commands); + } + get commandIDs() { + if (!this.commandsDir) + return []; + let globby; + try { + const globbyPath = require.resolve('globby', { paths: [this.root, __dirname] }); + globby = require(globbyPath); + } + catch (error) { + this.warn(error, 'not loading commands, globby not found'); + return []; + } + this._debug(`loading IDs from ${this.commandsDir}`); + const patterns = [ + '**/*.+(js|cjs|mjs|ts|tsx)', + '!**/*.+(d.ts|test.ts|test.js|spec.ts|spec.js)?(x)', + ]; + const ids = globby.sync(patterns, { cwd: this.commandsDir }) + .map(file => { + const p = path.parse(file); + const topics = p.dir.split('/'); + const command = p.name !== 'index' && p.name; + return [...topics, command].filter(f => f).join(':'); + }); + this._debug('found commands', ids); + return ids; + } + async findCommand(id, opts = {}) { + const fetch = async () => { + if (!this.commandsDir) + return; + const search = (cmd) => { + if (typeof cmd.run === 'function') + return cmd; + if (cmd.default && cmd.default.run) + return cmd.default; + return Object.values(cmd).find((cmd) => typeof cmd.run === 'function'); + }; + let m; + try { + const p = path.join(this.pjson.oclif.commands, ...id.split(':')); + const { isESM, module, filePath } = await module_loader_1.default.loadWithData(this, p); + this._debug(isESM ? '(import)' : '(require)', filePath); + m = module; + } + catch (error) { + if (!opts.must && error.code === 'MODULE_NOT_FOUND') + return; + throw error; + } + const cmd = search(m); + if (!cmd) + return; + cmd.id = id; + cmd.plugin = this; + return cmd; + }; + const cmd = await fetch(); + if (!cmd && opts.must) + (0, errors_1.error)(`command ${id} not found`); + return cmd; + } + async _manifest(ignoreManifest, errorOnManifestCreate = false) { + const readManifest = async (dotfile = false) => { + try { + const p = path.join(this.root, `${dotfile ? '.' : ''}oclif.manifest.json`); + const manifest = await (0, util_3.loadJSON)(p); + if (!process.env.OCLIF_NEXT_VERSION && manifest.version.split('-')[0] !== this.version.split('-')[0]) { + process.emitWarning(`Mismatched version in ${this.name} plugin manifest. Expected: ${this.version} Received: ${manifest.version}\nThis usually means you have an oclif.manifest.json file that should be deleted in development. This file should be automatically generated when publishing.`); + } + else { + this._debug('using manifest from', p); + return manifest; + } + } + catch (error) { + if (error.code === 'ENOENT') { + if (!dotfile) + return readManifest(true); + } + else { + this.warn(error, 'readManifest'); + } + } + }; + if (!ignoreManifest) { + const manifest = await readManifest(); + if (manifest) + return manifest; + } + return { + version: this.version, + commands: (await Promise.all(this.commandIDs.map(async (id) => { + try { + return [id, await (0, config_1.toCached)(await this.findCommand(id, { must: true }), this)]; + } + catch (error) { + const scope = 'toCached'; + if (Boolean(errorOnManifestCreate) === false) + this.warn(error, scope); + else + throw this.addErrorScope(error, scope); + } + }))) + .filter((f) => Boolean(f)) + .reduce((commands, [id, c]) => { + commands[id] = c; + return commands; + }, {}), + }; + } + warn(err, scope) { + if (this.warned) + return; + if (typeof err === 'string') + err = new Error(err); + process.emitWarning(this.addErrorScope(err, scope)); + } + addErrorScope(err, scope) { + err.name = `${err.name} Plugin: ${this.name}`; + err.detail = (0, util_3.compact)([err.detail, `module: ${this._base}`, scope && `task: ${scope}`, `plugin: ${this.name}`, `root: ${this.root}`, 'See more details with DEBUG=*']).join('\n'); + return err; + } +} +exports.Plugin = Plugin; /***/ }), -/***/ 63600: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* MIT license */ -/* eslint-disable no-mixed-operators */ -const cssKeywords = __nccwpck_require__(93732); +/***/ 3692: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) +"use strict"; -const reverseKeywords = {}; -for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.tsPath = void 0; +const fs = __nccwpck_require__(57147); +const path = __nccwpck_require__(71017); +const settings_1 = __nccwpck_require__(86464); +const util_1 = __nccwpck_require__(40765); +const util_2 = __nccwpck_require__(38008); +// eslint-disable-next-line new-cap +const debug = (0, util_2.Debug)('ts-node'); +function loadTSConfig(root) { + const tsconfigPath = path.join(root, 'tsconfig.json'); + let typescript; + try { + typescript = __nccwpck_require__(4440); + } + catch { + try { + typescript = require(root + '/node_modules/typescript'); + } + catch { } + } + if (fs.existsSync(tsconfigPath) && typescript) { + const tsconfig = typescript.parseConfigFileTextToJson(tsconfigPath, fs.readFileSync(tsconfigPath, 'utf8')).config; + if (!tsconfig || !tsconfig.compilerOptions) { + throw new Error(`Could not read and parse tsconfig.json at ${tsconfigPath}, or it ` + + 'did not contain a "compilerOptions" section.'); + } + return tsconfig; + } } +function tsPath(root, orig) { + if (!orig) + return orig; + orig = path.join(root, orig); + const skipTSNode = + // the CLI specifically turned it off + (settings_1.settings.tsnodeEnabled === false) || + // the CLI didn't specify ts-node and it is production + (settings_1.settings.tsnodeEnabled === undefined && (0, util_1.isProd)()); + if (skipTSNode) + return orig; + try { + const tsconfig = loadTSConfig(root); + if (!tsconfig) + return orig; + const { rootDir, rootDirs, outDir } = tsconfig.compilerOptions; + const rootDirPath = rootDir || (rootDirs || [])[0]; + if (!rootDirPath || !outDir) + return orig; + // rewrite path from ./lib/foo to ./src/foo + const lib = path.join(root, outDir); // ./lib + const src = path.join(root, rootDirPath); // ./src + const relative = path.relative(lib, orig); // ./commands + // For hooks, it might point to a js file, not a module. Something like "./hooks/myhook.js" which doesn't need the js. + const out = path.join(src, relative).replace(/\.js$/, ''); // ./src/commands + // this can be a directory of commands or point to a hook file + // if it's a directory, we check if the path exists. If so, return the path to the directory. + // For hooks, it might point to a module, not a file. Something like "./hooks/myhook" + // That file doesn't exist, and the real file is "./hooks/myhook.ts" + // In that case we attempt to resolve to the filename. If it fails it will revert back to the lib path + if (fs.existsSync(out) || fs.existsSync(out + '.ts')) + return out; + return orig; + } + catch (error) { + debug(error); + return orig; + } +} +exports.tsPath = tsPath; -const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -module.exports = convert; -// Hide .channels and .labels properties -for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } +/***/ }), - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } +/***/ 38008: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } +"use strict"; - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.collectUsableIds = exports.getCommandIdPermutations = exports.getPermutations = exports.Debug = exports.uniq = exports.compact = exports.loadJSON = exports.resolvePackage = exports.exists = exports.mapValues = exports.flatMap = void 0; +const fs = __nccwpck_require__(57147); +const debug = __nccwpck_require__(38237); +function flatMap(arr, fn) { + return arr.reduce((arr, i) => arr.concat(fn(i)), []); } +exports.flatMap = flatMap; +function mapValues(obj, fn) { + return Object.entries(obj) + .reduce((o, [k, v]) => { + o[k] = fn(v, k); + return o; + }, {}); +} +exports.mapValues = mapValues; +function exists(path) { + // eslint-disable-next-line no-promise-executor-return + return new Promise(resolve => resolve(fs.existsSync(path))); +} +exports.exists = exists; +function resolvePackage(id, paths) { + return require.resolve(id, paths); +} +exports.resolvePackage = resolvePackage; +function loadJSON(path) { + debug('config')('loadJSON %s', path); + return new Promise((resolve, reject) => { + fs.readFile(path, 'utf8', (err, d) => { + try { + if (err) + reject(err); + else + resolve(JSON.parse(d)); + } + catch (error) { + reject(error); + } + }); + }); +} +exports.loadJSON = loadJSON; +function compact(a) { + return a.filter((a) => Boolean(a)); +} +exports.compact = compact; +function uniq(arr) { + return [...new Set(arr)].sort(); +} +exports.uniq = uniq; +function displayWarnings() { + if (process.listenerCount('warning') > 1) + return; + process.on('warning', (warning) => { + console.error(warning.stack); + if (warning.detail) + console.error(warning.detail); + }); +} +function Debug(...scope) { + if (!debug) + return (..._) => { }; + const d = debug(['config', ...scope].join(':')); + if (d.enabled) + displayWarnings(); + return (...args) => d(...args); +} +exports.Debug = Debug; +// Adapted from https://github.com/angus-c/just/blob/master/packages/array-permutations/index.js +function getPermutations(arr) { + if (arr.length === 0) + return []; + if (arr.length === 1) + return [arr]; + const output = []; + const partialPermutations = getPermutations(arr.slice(1)); + const first = arr[0]; + for (let i = 0, len = partialPermutations.length; i < len; i++) { + const partial = partialPermutations[i]; + for (let j = 0, len2 = partial.length; j <= len2; j++) { + const start = partial.slice(0, j); + const end = partial.slice(j); + const merged = start.concat(first, end); + output.push(merged); + } + } + return output; +} +exports.getPermutations = getPermutations; +function getCommandIdPermutations(commandId) { + return getPermutations(commandId.split(':')).flatMap(c => c.join(':')); +} +exports.getCommandIdPermutations = getCommandIdPermutations; +/** + * Return an array of ids that represent all the usable combinations that a user could enter. + * + * For example, if the command ids are: + * - foo:bar:baz + * - one:two:three + * Then the usable ids would be: + * - foo + * - foo:bar + * - foo:bar:baz + * - one + * - one:two + * - one:two:three + * + * This allows us to determine which parts of the argv array belong to the command id whenever the topicSeparator is a space. + * + * @param commandIds string[] + * @returns string[] + */ +function collectUsableIds(commandIds) { + const usuableIds = []; + for (const id of commandIds) { + const parts = id.split(':'); + while (parts.length > 0) { + const name = parts.join(':'); + if (name) + usuableIds.push(name); + parts.pop(); + } + } + return uniq(usuableIds).sort(); +} +exports.collectUsableIds = collectUsableIds; -convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - if (h < 0) { - h += 360; - } +/***/ }), - const l = (min + max) / 2; +/***/ 75383: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } +"use strict"; - return [h, s * 100, l * 100]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.config = void 0; +const settings_1 = __nccwpck_require__(86464); +const logger_1 = __nccwpck_require__(69599); +function displayWarnings() { + if (process.listenerCount('warning') > 1) + return; + process.on('warning', (warning) => { + console.error(warning.stack); + if (warning.detail) + console.error(warning.detail); + }); +} +exports.config = { + errorLogger: undefined, + get debug() { + return Boolean(settings_1.settings.debug); + }, + set debug(enabled) { + settings_1.settings.debug = enabled; + if (enabled) + displayWarnings(); + }, + get errlog() { + return settings_1.settings.errlog; + }, + set errlog(errlog) { + if (errlog) { + this.errorLogger = new logger_1.Logger(errlog); + settings_1.settings.errlog = errlog; + } + else { + delete this.errorLogger; + delete settings_1.settings.errlog; + } + }, }; -convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; +/***/ }), - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); +/***/ 68463: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } +"use strict"; - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CLIError = exports.addOclifExitCode = void 0; +const chalk = __nccwpck_require__(1854); +const indent = __nccwpck_require__(98043); +const cs = __nccwpck_require__(27972); +const wrap = __nccwpck_require__(59824); +const screen = __nccwpck_require__(12051); +const config_1 = __nccwpck_require__(75383); +/** + * properties specific to internal oclif error handling + */ +function addOclifExitCode(error, options) { + if (!('oclif' in error)) { + error.oclif = {}; + } + error.oclif.exit = (options === null || options === void 0 ? void 0 : options.exit) === undefined ? 2 : options.exit; + return error; +} +exports.addOclifExitCode = addOclifExitCode; +class CLIError extends Error { + constructor(error, options = {}) { + super(error instanceof Error ? error.message : error); + this.oclif = {}; + addOclifExitCode(this, options); + this.code = options.code; + } + get stack() { + return cs(super.stack, { pretty: true }); + } + /** + * @deprecated `render` Errors display should be handled by display function, like pretty-print + * @return {string} returns a string representing the dispay of the error + */ + render() { + if (config_1.config.debug) { + return this.stack; + } + let output = `${this.name}: ${this.message}`; + output = wrap(output, screen.errtermwidth - 6, { trim: false, hard: true }); + output = indent(output, 3); + output = indent(output, 1, { indent: this.bang, includeEmptyLines: true }); + output = indent(output, 1); + return output; + } + get bang() { + try { + return chalk.red(process.platform === 'win32' ? '»' : '›'); + } + catch { } + } +} +exports.CLIError = CLIError; +(function (CLIError) { + class Warn extends CLIError { + constructor(err) { + super(err instanceof Error ? err.message : err); + this.name = 'Warning'; + } + get bang() { + try { + return chalk.yellow(process.platform === 'win32' ? '»' : '›'); + } + catch { } + } + } + CLIError.Warn = Warn; +})(CLIError = exports.CLIError || (exports.CLIError = {})); - return [ - h * 360, - s * 100, - v * 100 - ]; -}; -convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); +/***/ }), - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); +/***/ 30950: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [h, w * 100, b * 100]; -}; +"use strict"; -convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ExitError = void 0; +const cli_1 = __nccwpck_require__(68463); +class ExitError extends cli_1.CLIError { + constructor(exitCode = 1) { + super(`EEXIT: ${exitCode}`, { exit: exitCode }); + this.code = 'EEXIT'; + } + render() { + return ''; + } +} +exports.ExitError = ExitError; - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - return [c * 100, m * 100, y * 100, k * 100]; -}; +/***/ }), -function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); -} +/***/ 37053: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } +"use strict"; - let currentClosestDistance = Infinity; - let currentClosestKeyword; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ModuleLoadError = void 0; +const cli_1 = __nccwpck_require__(68463); +class ModuleLoadError extends cli_1.CLIError { + constructor(message) { + super(`[MODULE_NOT_FOUND] ${message}`, { exit: 1 }); + this.code = 'MODULE_NOT_FOUND'; + this.name = 'ModuleLoadError'; + } +} +exports.ModuleLoadError = ModuleLoadError; - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; - // Compute comparative distance - const distance = comparativeDistance(rgb, value); +/***/ }), - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } +/***/ 46914: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return currentClosestKeyword; -}; +"use strict"; -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.applyPrettyPrintOptions = void 0; +const wrap = __nccwpck_require__(59824); +const indent = __nccwpck_require__(98043); +const screen = __nccwpck_require__(12051); +const config_1 = __nccwpck_require__(75383); +function applyPrettyPrintOptions(error, options) { + const prettyErrorKeys = ['message', 'code', 'ref', 'suggestions']; + for (const key of prettyErrorKeys) { + const applyOptionsKey = !(key in error) && options[key]; + if (applyOptionsKey) { + error[key] = options[key]; + } + } + return error; +} +exports.applyPrettyPrintOptions = applyPrettyPrintOptions; +const formatSuggestions = (suggestions) => { + const label = 'Try this:'; + if (!suggestions || suggestions.length === 0) + return undefined; + if (suggestions.length === 1) + return `${label} ${suggestions[0]}`; + const multiple = suggestions.map(suggestion => `* ${suggestion}`).join('\n'); + return `${label}\n${indent(multiple, 2)}`; }; +function prettyPrint(error) { + if (config_1.config.debug) { + return error.stack; + } + const { message, code, suggestions, ref, name: errorSuffix, bang } = error; + // errorSuffix is pulled from the 'name' property on CLIError + // and is like either Error or Warning + const formattedHeader = message ? `${errorSuffix || 'Error'}: ${message}` : undefined; + const formattedCode = code ? `Code: ${code}` : undefined; + const formattedSuggestions = formatSuggestions(suggestions); + const formattedReference = ref ? `Reference: ${ref}` : undefined; + const formatted = [formattedHeader, formattedCode, formattedSuggestions, formattedReference] + .filter(Boolean) + .join('\n'); + let output = wrap(formatted, screen.errtermwidth - 6, { trim: false, hard: true }); + output = indent(output, 3); + output = indent(output, 1, { indent: bang || '', includeEmptyLines: true }); + output = indent(output, 1); + return output; +} +exports["default"] = prettyPrint; -convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); +/***/ }), - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); +/***/ 77463: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [x * 100, y * 100, z * 100]; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.handle = void 0; +/* eslint-disable no-process-exit */ +/* eslint-disable unicorn/no-process-exit */ +const config_1 = __nccwpck_require__(75383); +const pretty_print_1 = __nccwpck_require__(46914); +const _1 = __nccwpck_require__(34630); +const clean = __nccwpck_require__(27972); +const cli_1 = __nccwpck_require__(68463); +const handle = (err) => { + var _a, _b, _c; + try { + if (!err) + err = new cli_1.CLIError('no error?'); + if (err.message === 'SIGINT') + process.exit(1); + const shouldPrint = !(err instanceof _1.ExitError); + const pretty = (0, pretty_print_1.default)(err); + const stack = clean(err.stack || '', { pretty: true }); + if (shouldPrint) { + console.error(pretty ? pretty : stack); + } + const exitCode = ((_a = err.oclif) === null || _a === void 0 ? void 0 : _a.exit) !== undefined && ((_b = err.oclif) === null || _b === void 0 ? void 0 : _b.exit) !== false ? (_c = err.oclif) === null || _c === void 0 ? void 0 : _c.exit : 1; + if (config_1.config.errorLogger && err.code !== 'EEXIT') { + if (stack) { + config_1.config.errorLogger.log(stack); + } + config_1.config.errorLogger.flush() + .then(() => process.exit(exitCode)) + .catch(console.error); + } + else + process.exit(exitCode); + } + catch (error) { + console.error(err.stack); + console.error(error.stack); + process.exit(1); + } }; +exports.handle = handle; -convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - x /= 95.047; - y /= 100; - z /= 108.883; +/***/ }), - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); +/***/ 34630: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); +"use strict"; - return [l, a, b]; -}; +// tslint:disable no-console +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.warn = exports.error = exports.exit = exports.config = exports.Logger = exports.CLIError = exports.ModuleLoadError = exports.ExitError = exports.handle = void 0; +var handle_1 = __nccwpck_require__(77463); +Object.defineProperty(exports, "handle", ({ enumerable: true, get: function () { return handle_1.handle; } })); +var exit_1 = __nccwpck_require__(30950); +Object.defineProperty(exports, "ExitError", ({ enumerable: true, get: function () { return exit_1.ExitError; } })); +var module_load_1 = __nccwpck_require__(37053); +Object.defineProperty(exports, "ModuleLoadError", ({ enumerable: true, get: function () { return module_load_1.ModuleLoadError; } })); +var cli_1 = __nccwpck_require__(68463); +Object.defineProperty(exports, "CLIError", ({ enumerable: true, get: function () { return cli_1.CLIError; } })); +var logger_1 = __nccwpck_require__(69599); +Object.defineProperty(exports, "Logger", ({ enumerable: true, get: function () { return logger_1.Logger; } })); +var config_1 = __nccwpck_require__(75383); +Object.defineProperty(exports, "config", ({ enumerable: true, get: function () { return config_1.config; } })); +const config_2 = __nccwpck_require__(75383); +const cli_2 = __nccwpck_require__(68463); +const exit_2 = __nccwpck_require__(30950); +const pretty_print_1 = __nccwpck_require__(46914); +function exit(code = 0) { + throw new exit_2.ExitError(code); +} +exports.exit = exit; +function error(input, options = {}) { + var _a; + let err; + if (typeof input === 'string') { + err = new cli_2.CLIError(input, options); + } + else if (input instanceof Error) { + err = (0, cli_2.addOclifExitCode)(input, options); + } + else { + throw new TypeError('first argument must be a string or instance of Error'); + } + err = (0, pretty_print_1.applyPrettyPrintOptions)(err, options); + if (options.exit === false) { + const message = (0, pretty_print_1.default)(err); + console.error(message); + if (config_2.config.errorLogger) + config_2.config.errorLogger.log((_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : ''); + } + else + throw err; +} +exports.error = error; +function warn(input) { + var _a; + let err; + if (typeof input === 'string') { + err = new cli_2.CLIError.Warn(input); + } + else if (input instanceof Error) { + err = (0, cli_2.addOclifExitCode)(input); + } + else { + throw new TypeError('first argument must be a string or instance of Error'); + } + const message = (0, pretty_print_1.default)(err); + console.error(message); + if (config_2.config.errorLogger) + config_2.config.errorLogger.log((_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : ''); +} +exports.warn = warn; -convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - if (s === 0) { - val = l * 255; - return [val, val, val]; - } +/***/ }), - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } +/***/ 69599: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const t1 = 2 * l - t2; +"use strict"; - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Logger = void 0; +const path = __nccwpck_require__(71017); +const timestamp = () => new Date().toISOString(); +let timer; +const wait = (ms) => new Promise(resolve => { + if (timer) + timer.unref(); + timer = setTimeout(() => resolve(null), ms); +}); +function chomp(s) { + if (s.endsWith('\n')) + return s.replace(/\n$/, ''); + return s; +} +class Logger { + // eslint-disable-next-line no-useless-constructor + constructor(file) { + this.file = file; + this.flushing = Promise.resolve(); + this.buffer = []; + } + log(msg) { + const stripAnsi = __nccwpck_require__(45591); + msg = stripAnsi(chomp(msg)); + const lines = msg.split('\n').map(l => `${timestamp()} ${l}`.trimEnd()); + this.buffer.push(...lines); + // tslint:disable-next-line no-console + this.flush(50).catch(console.error); + } + async flush(waitForMs = 0) { + await wait(waitForMs); + this.flushing = this.flushing.then(async () => { + if (this.buffer.length === 0) + return; + const mylines = this.buffer; + this.buffer = []; + const fs = __nccwpck_require__(39035); + await fs.mkdirp(path.dirname(this.file)); + await fs.appendFile(this.file, mylines.join('\n') + '\n'); + }); + await this.flushing; + } +} +exports.Logger = Logger; - if (t3 > 1) { - t3--; - } - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } +/***/ }), - rgb[i] = val * 255; - } +/***/ 78251: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return rgb; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.help = exports.version = exports.file = exports.directory = exports.url = exports.integer = exports.boolean = exports.string = exports["enum"] = exports.option = exports.build = void 0; +const Parser = __nccwpck_require__(44195); +function build(defaults) { + return Parser.flags.build(defaults); +} +exports.build = build; +function option(options) { + return build(options)(); +} +exports.option = option; +const _enum = (opts) => { + return build({ + async parse(input) { + if (!opts.options.includes(input)) + throw new Error(`Expected --${this.name}=${input} to be one of: ${opts.options.join(', ')}`); + return input; + }, + helpValue: `(${opts.options.join('|')})`, + ...opts, + })(); +}; +exports["enum"] = _enum; +const stringFlag = build({}); +exports.string = stringFlag; +var parser_1 = __nccwpck_require__(44195); +Object.defineProperty(exports, "boolean", ({ enumerable: true, get: function () { return parser_1.boolean; } })); +Object.defineProperty(exports, "integer", ({ enumerable: true, get: function () { return parser_1.integer; } })); +Object.defineProperty(exports, "url", ({ enumerable: true, get: function () { return parser_1.url; } })); +Object.defineProperty(exports, "directory", ({ enumerable: true, get: function () { return parser_1.directory; } })); +Object.defineProperty(exports, "file", ({ enumerable: true, get: function () { return parser_1.file; } })); +const version = (opts = {}) => { + return Parser.flags.boolean({ + description: 'Show CLI version.', + ...opts, + parse: async (_, cmd) => { + cmd.log(cmd.config.userAgent); + cmd.exit(0); + }, + }); +}; +exports.version = version; +const help = (opts = {}) => { + return Parser.flags.boolean({ + description: 'Show CLI help.', + ...opts, + parse: async (_, cmd) => { + cmd._help(); + }, + }); }; +exports.help = help; -convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); +/***/ }), - return [h, sv * 100, v * 100]; -}; +/***/ 80925: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; +"use strict"; -convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommandHelp = void 0; +const Chalk = __nccwpck_require__(1854); +const stripAnsi = __nccwpck_require__(45591); +const util_1 = __nccwpck_require__(40765); +const formatter_1 = __nccwpck_require__(39513); +const docopts_1 = __nccwpck_require__(44021); +// Don't use os.EOL because we need to ensure that a string +// written on any platform, that may use \r\n or \n, will be +// split on any platform, not just the os specific EOL at runtime. +const POSSIBLE_LINE_FEED = /\r\n|\n/; +const { underline, } = Chalk; +let { dim, } = Chalk; +if (process.env.ConEmuANSI === 'ON') { + // eslint-disable-next-line unicorn/consistent-destructuring + dim = Chalk.gray; +} +class CommandHelp extends formatter_1.HelpFormatter { + constructor(command, config, opts) { + super(config, opts); + this.command = command; + this.config = config; + this.opts = opts; + } + generate() { + const cmd = this.command; + const flags = (0, util_1.sortBy)(Object.entries(cmd.flags || {}) + .filter(([, v]) => !v.hidden) + .map(([k, v]) => { + v.name = k; + return v; + }), f => [!f.char, f.char, f.name]); + const args = (cmd.args || []).filter(a => !a.hidden); + const output = (0, util_1.compact)(this.sections().map(({ header, generate }) => { + const body = generate({ cmd, flags, args }, header); + // Generate can return a list of sections + if (Array.isArray(body)) { + return body.map(helpSection => helpSection && helpSection.body && this.section(helpSection.header, helpSection.body)).join('\n\n'); + } + return body && this.section(header, body); + })).join('\n\n'); + return output; + } + groupFlags(flags) { + const mainFlags = []; + const flagGroups = {}; + for (const flag of flags) { + const group = flag.helpGroup; + if (group) { + if (!flagGroups[group]) + flagGroups[group] = []; + flagGroups[group].push(flag); + } + else { + mainFlags.push(flag); + } + } + return { mainFlags, flagGroups }; + } + sections() { + return [ + { + header: this.opts.usageHeader || 'USAGE', + generate: () => this.usage(), + }, + { + header: 'ARGUMENTS', + generate: ({ args }, header) => [{ header, body: this.args(args) }], + }, + { + header: 'FLAGS', + generate: ({ flags }, header) => { + const { mainFlags, flagGroups } = this.groupFlags(flags); + const flagSections = []; + const mainFlagBody = this.flags(mainFlags); + if (mainFlagBody) + flagSections.push({ header, body: mainFlagBody }); + for (const [name, flags] of Object.entries(flagGroups)) { + const body = this.flags(flags); + if (body) + flagSections.push({ header: `${name.toUpperCase()} ${header}`, body }); + } + return (0, util_1.compact)(flagSections); + }, + }, + { + header: 'DESCRIPTION', + generate: () => this.description(), + }, + { + header: 'ALIASES', + generate: ({ cmd }) => this.aliases(cmd.aliases), + }, + { + header: 'EXAMPLES', + generate: ({ cmd }) => { + const examples = cmd.examples || cmd.example; + return this.examples(examples); + }, + }, + { + header: 'FLAG DESCRIPTIONS', + generate: ({ flags }) => this.flagsDescriptions(flags), + }, + ]; + } + usage() { + const usage = this.command.usage; + const body = (usage ? (0, util_1.castArray)(usage) : [this.defaultUsage()]) + .map(u => { + const allowedSpacing = this.opts.maxWidth - this.indentSpacing; + const line = `$ ${this.config.bin} ${u}`.trim(); + if (line.length > allowedSpacing) { + const splitIndex = line.slice(0, Math.max(0, allowedSpacing)).lastIndexOf(' '); + return line.slice(0, Math.max(0, splitIndex)) + '\n' + + this.indent(this.wrap(line.slice(Math.max(0, splitIndex)), this.indentSpacing * 2)); + } + return this.wrap(line); + }) + .join('\n'); + return body; + } + defaultUsage() { + // Docopts by default + if (this.opts.docopts === undefined || this.opts.docopts) { + return docopts_1.DocOpts.generate(this.command); + } + return (0, util_1.compact)([ + this.command.id, + this.command.args.filter(a => !a.hidden).map(a => this.arg(a)).join(' '), + ]).join(' '); + } + description() { + const cmd = this.command; + let description; + if (this.opts.hideCommandSummaryInDescription) { + description = (cmd.description || '').split(POSSIBLE_LINE_FEED).slice(1); + } + else if (cmd.description) { + description = [ + ...(cmd.summary || '').split(POSSIBLE_LINE_FEED), + ...(cmd.description || '').split(POSSIBLE_LINE_FEED), + ]; + } + if (description) { + // Lines separated with only one newline or more than 2 can be hard to read in the terminal. + // Always separate by two newlines. + return this.wrap((0, util_1.compact)(description).join('\n\n')); + } + } + aliases(aliases) { + if (!aliases || aliases.length === 0) + return; + const body = aliases.map(a => ['$', this.config.bin, a].join(' ')).join('\n'); + return body; + } + examples(examples) { + if (!examples || examples.length === 0) + return; + const formatIfCommand = (example) => { + example = this.render(example); + if (example.startsWith(this.config.bin)) + return dim(`$ ${example}`); + if (example.startsWith(`$ ${this.config.bin}`)) + return dim(example); + return example; + }; + const isCommand = (example) => stripAnsi(formatIfCommand(example)).startsWith(`$ ${this.config.bin}`); + const body = (0, util_1.castArray)(examples).map(a => { + let description; + let commands; + if (typeof a === 'string') { + const lines = a + .split(POSSIBLE_LINE_FEED) + .filter(line => Boolean(line)); + // If the example is \n then format correctly + // eslint-disable-next-line unicorn/no-array-callback-reference + if (lines.length >= 2 && !isCommand(lines[0]) && lines.slice(1).every(isCommand)) { + description = lines[0]; + commands = lines.slice(1); + } + else { + return lines.map(line => formatIfCommand(line)).join('\n'); + } + } + else { + description = a.description; + commands = [a.command]; + } + const multilineSeparator = this.config.platform === 'win32' ? + (this.config.shell.includes('powershell') ? '`' : '^') : + '\\'; + // The command will be indented in the section, which is also indented + const finalIndentedSpacing = this.indentSpacing * 2; + const multilineCommands = commands.map(c => { + // First indent keeping room for escaped newlines + return this.indent(this.wrap(formatIfCommand(c), finalIndentedSpacing + 4)) + // Then add the escaped newline + .split(POSSIBLE_LINE_FEED).join(` ${multilineSeparator}\n `); + }).join('\n'); + return `${this.wrap(description, finalIndentedSpacing)}\n\n${multilineCommands}`; + }).join('\n\n'); + return body; + } + args(args) { + if (args.filter(a => a.description).length === 0) + return; + return args.map(a => { + const name = a.name.toUpperCase(); + let description = a.description || ''; + if (a.default) + description = `[default: ${a.default}] ${description}`; + if (a.options) + description = `(${a.options.join('|')}) ${description}`; + return [name, description ? dim(description) : undefined]; + }); + } + arg(arg) { + const name = arg.name.toUpperCase(); + if (arg.required) + return `${name}`; + return `[${name}]`; + } + flagHelpLabel(flag, showOptions = false) { + let label = flag.helpLabel; + if (!label) { + const labels = []; + if (flag.char) + labels.push(`-${flag.char[0]}`); + if (flag.name) { + if (flag.type === 'boolean' && flag.allowNo) { + labels.push(`--[no-]${flag.name.trim()}`); + } + else { + labels.push(`--${flag.name.trim()}`); + } + } + label = labels.join(', '); + } + if (flag.type === 'option') { + let value = flag.helpValue || (this.opts.showFlagNameInTitle ? flag.name : ''); + if (!flag.helpValue && flag.options) { + value = showOptions || this.opts.showFlagOptionsInTitle ? `${flag.options.join('|')}` : '