UNPKG

@kitschpatrol/typescript-config

Version:
1,400 lines (1,382 loc) 225 kB
#!/usr/bin/env node import { createRequire } from "module"; const require = createRequire(import.meta.url); var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js var require_picocolors = __commonJS({ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) { var p = process || {}; var argv = p.argv || []; var env2 = p.env || {}; var isColorSupported = !(!!env2.NO_COLOR || argv.includes("--no-color")) && (!!env2.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env2.TERM !== "dumb" || !!env2.CI); var formatter = (open, close, replace = open) => (input) => { let string = "" + input, index = string.indexOf(close, open.length); return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; }; var replaceClose = (string, close, replace, index) => { let result = "", cursor = 0; do { result += string.substring(cursor, index) + replace; cursor = index + close.length; index = string.indexOf(close, cursor); } while (~index); return result + string.substring(cursor); }; var createColors = (enabled = isColorSupported) => { let f = enabled ? formatter : () => String; return { isColorSupported: enabled, reset: f("\x1B[0m", "\x1B[0m"), bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), italic: f("\x1B[3m", "\x1B[23m"), underline: f("\x1B[4m", "\x1B[24m"), inverse: f("\x1B[7m", "\x1B[27m"), hidden: f("\x1B[8m", "\x1B[28m"), strikethrough: f("\x1B[9m", "\x1B[29m"), black: f("\x1B[30m", "\x1B[39m"), red: f("\x1B[31m", "\x1B[39m"), green: f("\x1B[32m", "\x1B[39m"), yellow: f("\x1B[33m", "\x1B[39m"), blue: f("\x1B[34m", "\x1B[39m"), magenta: f("\x1B[35m", "\x1B[39m"), cyan: f("\x1B[36m", "\x1B[39m"), white: f("\x1B[37m", "\x1B[39m"), gray: f("\x1B[90m", "\x1B[39m"), bgBlack: f("\x1B[40m", "\x1B[49m"), bgRed: f("\x1B[41m", "\x1B[49m"), bgGreen: f("\x1B[42m", "\x1B[49m"), bgYellow: f("\x1B[43m", "\x1B[49m"), bgBlue: f("\x1B[44m", "\x1B[49m"), bgMagenta: f("\x1B[45m", "\x1B[49m"), bgCyan: f("\x1B[46m", "\x1B[49m"), bgWhite: f("\x1B[47m", "\x1B[49m"), blackBright: f("\x1B[90m", "\x1B[39m"), redBright: f("\x1B[91m", "\x1B[39m"), greenBright: f("\x1B[92m", "\x1B[39m"), yellowBright: f("\x1B[93m", "\x1B[39m"), blueBright: f("\x1B[94m", "\x1B[39m"), magentaBright: f("\x1B[95m", "\x1B[39m"), cyanBright: f("\x1B[96m", "\x1B[39m"), whiteBright: f("\x1B[97m", "\x1B[39m"), bgBlackBright: f("\x1B[100m", "\x1B[49m"), bgRedBright: f("\x1B[101m", "\x1B[49m"), bgGreenBright: f("\x1B[102m", "\x1B[49m"), bgYellowBright: f("\x1B[103m", "\x1B[49m"), bgBlueBright: f("\x1B[104m", "\x1B[49m"), bgMagentaBright: f("\x1B[105m", "\x1B[49m"), bgCyanBright: f("\x1B[106m", "\x1B[49m"), bgWhiteBright: f("\x1B[107m", "\x1B[49m") }; }; module.exports = createColors(); module.exports.createColors = createColors; } }); // ../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js var require_cjs = __commonJS({ "../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"(exports, module) { "use strict"; var isMergeableObject = function isMergeableObject2(value) { return isNonNullObject(value) && !isSpecial(value); }; function isNonNullObject(value) { return !!value && typeof value === "object"; } function isSpecial(value) { var stringValue = Object.prototype.toString.call(value); return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value); } var canUseSymbol = typeof Symbol === "function" && Symbol.for; var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103; function isReactElement(value) { return value.$$typeof === REACT_ELEMENT_TYPE; } function emptyTarget(val) { return Array.isArray(val) ? [] : {}; } function cloneUnlessOtherwiseSpecified(value, options) { return options.clone !== false && options.isMergeableObject(value) ? deepmerge2(emptyTarget(value), value, options) : value; } function defaultArrayMerge(target, source, options) { return target.concat(source).map(function(element) { return cloneUnlessOtherwiseSpecified(element, options); }); } function getMergeFunction(key, options) { if (!options.customMerge) { return deepmerge2; } var customMerge = options.customMerge(key); return typeof customMerge === "function" ? customMerge : deepmerge2; } function getEnumerableOwnPropertySymbols(target) { return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) { return Object.propertyIsEnumerable.call(target, symbol); }) : []; } function getKeys(target) { return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)); } function propertyIsOnObject(object, property) { try { return property in object; } catch (_) { return false; } } function propertyIsUnsafe(target, key) { return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key)); } function mergeObject(target, source, options) { var destination = {}; if (options.isMergeableObject(target)) { getKeys(target).forEach(function(key) { destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); }); } getKeys(source).forEach(function(key) { if (propertyIsUnsafe(target, key)) { return; } if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { destination[key] = getMergeFunction(key, options)(target[key], source[key], options); } else { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); } }); return destination; } function deepmerge2(target, source, options) { options = options || {}; options.arrayMerge = options.arrayMerge || defaultArrayMerge; options.isMergeableObject = options.isMergeableObject || isMergeableObject; options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; var sourceIsArray = Array.isArray(source); var targetIsArray = Array.isArray(target); var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; if (!sourceAndTargetTypesMatch) { return cloneUnlessOtherwiseSpecified(source, options); } else if (sourceIsArray) { return options.arrayMerge(target, source, options); } else { return mergeObject(target, source, options); } } deepmerge2.all = function deepmergeAll(array, options) { if (!Array.isArray(array)) { throw new Error("first argument should be an array"); } return array.reduce(function(prev, next) { return deepmerge2(prev, next, options); }, {}); }; var deepmerge_1 = deepmerge2; module.exports = deepmerge_1; } }); // ../../src/command-builder.ts import { cosmiconfig } from "cosmiconfig"; import { TypeScriptLoader as typeScriptLoader } from "cosmiconfig-typescript-loader"; import { execa } from "execa"; import fse2 from "fs-extra"; import fs3 from "node:fs"; import path3 from "node:path"; import { PassThrough } from "node:stream"; import { fileURLToPath as fileURLToPath3 } from "node:url"; // ../../node_modules/.pnpm/package-up@5.0.0/node_modules/package-up/index.js import process3 from "node:process"; // ../../node_modules/.pnpm/find-up-simple@1.0.1/node_modules/find-up-simple/index.js import process2 from "node:process"; import fsPromises from "node:fs/promises"; import { fileURLToPath } from "node:url"; import fs from "node:fs"; import path from "node:path"; var toPath = (urlOrPath) => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; async function findUp(name, { cwd = process2.cwd(), type = "file", stopAt } = {}) { let directory = path.resolve(toPath(cwd) ?? ""); const { root } = path.parse(directory); stopAt = path.resolve(directory, toPath(stopAt ?? root)); const isAbsoluteName = path.isAbsolute(name); while (directory) { const filePath = isAbsoluteName ? name : path.join(directory, name); try { const stats = await fsPromises.stat(filePath); if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) { return filePath; } } catch { } if (directory === stopAt || directory === root) { break; } directory = path.dirname(directory); } } function findUpSync(name, { cwd = process2.cwd(), type = "file", stopAt } = {}) { let directory = path.resolve(toPath(cwd) ?? ""); const { root } = path.parse(directory); stopAt = path.resolve(directory, toPath(stopAt) ?? root); const isAbsoluteName = path.isAbsolute(name); while (directory) { const filePath = isAbsoluteName ? name : path.join(directory, name); try { const stats = fs.statSync(filePath, { throwIfNoEntry: false }); if (type === "file" && stats?.isFile() || type === "directory" && stats?.isDirectory()) { return filePath; } } catch { } if (directory === stopAt || directory === root) { break; } directory = path.dirname(directory); } } // ../../node_modules/.pnpm/package-up@5.0.0/node_modules/package-up/index.js async function packageUp({ cwd = process3.cwd() } = {}) { return findUp("package.json", { cwd }); } function packageUpSync({ cwd = process3.cwd() } = {}) { return findUpSync("package.json", { cwd }); } // ../../src/command-builder.ts var import_picocolors2 = __toESM(require_picocolors(), 1); // ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/lib/platform-shims/esm.mjs import { notStrictEqual, strictEqual } from "assert"; // ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/index.js var align = { right: alignRight, center: alignCenter }; var top = 0; var right = 1; var bottom = 2; var left = 3; var UI = class { constructor(opts) { var _a2; this.width = opts.width; this.wrap = (_a2 = opts.wrap) !== null && _a2 !== void 0 ? _a2 : true; this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(""); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === "string") { return this.applyLayoutDSL(args[0]); } const cols = args.map((arg) => { if (typeof arg === "string") { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === "string" && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split("\n").map((row) => row.split(" ")); let leftColumnWidth = 0; rows.forEach((columns) => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); rows.forEach((columns) => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: i === 0 && columns.length > 1 ? leftColumnWidth : void 0 }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach((row) => { this.rowToString(row, lines); }); return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n"); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ""; rrow.forEach((col, c) => { const { width } = row[c]; const wrapWidth = this.negatePadding(row[c]); let ts = col; if (wrapWidth > mixin.stringWidth(col)) { ts += " ".repeat(wrapWidth - mixin.stringWidth(col)); } if (row[c].align && row[c].align !== "left" && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { ts += " ".repeat((width || 0) - mixin.stringWidth(ts) - 1); } } const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += " ".repeat(padding[left]); } str += addBorder(row[c], ts, "| "); str += ts; str += addBorder(row[c], ts, " |"); if (padding[right]) { str += " ".repeat(padding[right]); } if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); lines.push({ text: str.replace(/ +$/, ""), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); const leadingWhitespace = match ? match[0].length : 0; const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimRight()); if (!previousLine.span) { return source; } if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; row.forEach((col, c) => { col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n"); } else { wrapped = col.text.split("\n"); } if (col.border) { wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + "."); wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'"); } if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill("")); wrapped.push(...new Array(col.padding[bottom] || 0).fill("")); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === void 0) { rrow.push(""); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { let wrapWidth = col.width || 0; if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map((col) => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; const widths = row.map((col) => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return void 0; }); const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; return widths.map((w, i) => { if (w === void 0) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } }; function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ""; } if (ts.trim().length !== 0) { return style; } return " "; } return ""; } function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { if (typeof process === "object" && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return " ".repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth >= width) { return str; } return " ".repeat(width - strWidth >> 1) + str; } var mixin; function cliui(opts, _mixin) { mixin = _mixin; return new UI({ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap }); } // ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/string-utils.js var ansi = new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", "g"); function stripAnsi(str) { return str.replace(ansi, ""); } function wrap(str, width) { const [start, end] = str.match(ansi) || ["", ""]; str = stripAnsi(str); let wrapped = ""; for (let i = 0; i < str.length; i++) { if (i !== 0 && i % width === 0) { wrapped += "\n"; } wrapped += str.charAt(i); } if (start && end) { wrapped = `${start}${wrapped}${end}`; } return wrapped; } // ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/index.mjs function ui(opts) { return cliui(opts, { stringWidth: (str) => { return [...str].length; }, stripAnsi, wrap }); } // ../../node_modules/.pnpm/escalade@3.2.0/node_modules/escalade/sync/index.mjs import { dirname, resolve } from "path"; import { readdirSync, statSync } from "fs"; function sync_default(start, callback) { let dir = resolve(".", start); let tmp, stats = statSync(dir); if (!stats.isDirectory()) { dir = dirname(dir); } while (true) { tmp = callback(dir, readdirSync(dir)); if (tmp) return resolve(dir, tmp); dir = dirname(tmp = dir); if (tmp === dir) break; } } // ../../node_modules/.pnpm/yargs@17.7.2/node_modules/yargs/lib/platform-shims/esm.mjs import { inspect } from "util"; import { readFileSync as readFileSync3 } from "fs"; import { fileURLToPath as fileURLToPath2 } from "url"; // ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/index.js import { format } from "util"; import { normalize, resolve as resolve2 } from "path"; // ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/string-utils.js function camelCase(str) { const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); if (!isCamelCase) { str = str.toLowerCase(); } if (str.indexOf("-") === -1 && str.indexOf("_") === -1) { return str; } else { let camelcase = ""; let nextChrUpper = false; const leadingHyphens = str.match(/^-+/); for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { let chr = str.charAt(i); if (nextChrUpper) { nextChrUpper = false; chr = chr.toUpperCase(); } if (i !== 0 && (chr === "-" || chr === "_")) { nextChrUpper = true; } else if (chr !== "-" && chr !== "_") { camelcase += chr; } } return camelcase; } } function decamelize(str, joinString) { const lowercase = str.toLowerCase(); joinString = joinString || "-"; let notCamelcase = ""; for (let i = 0; i < str.length; i++) { const chrLower = lowercase.charAt(i); const chrString = str.charAt(i); if (chrLower !== chrString && i > 0) { notCamelcase += `${joinString}${lowercase.charAt(i)}`; } else { notCamelcase += chrString; } } return notCamelcase; } function looksLikeNumber(x) { if (x === null || x === void 0) return false; if (typeof x === "number") return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; if (/^0[^.]/.test(x)) return false; return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } // ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/tokenize-arg-string.js function tokenizeArgString(argString) { if (Array.isArray(argString)) { return argString.map((e) => typeof e !== "string" ? e + "" : e); } argString = argString.trim(); let i = 0; let prevC = null; let c = null; let opening = null; const args = []; for (let ii = 0; ii < argString.length; ii++) { prevC = c; c = argString.charAt(ii); if (c === " " && !opening) { if (!(prevC === " ")) { i++; } continue; } if (c === opening) { opening = null; } else if ((c === "'" || c === '"') && !opening) { opening = c; } if (!args[i]) args[i] = ""; args[i] += c; } return args; } // ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser-types.js var DefaultValuesForTypeKey; (function(DefaultValuesForTypeKey2) { DefaultValuesForTypeKey2["BOOLEAN"] = "boolean"; DefaultValuesForTypeKey2["STRING"] = "string"; DefaultValuesForTypeKey2["NUMBER"] = "number"; DefaultValuesForTypeKey2["ARRAY"] = "array"; })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); // ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser.js var mixin2; var YargsParser = class { constructor(_mixin) { mixin2 = _mixin; } parse(argsInput, options) { const opts = Object.assign({ alias: void 0, array: void 0, boolean: void 0, config: void 0, configObjects: void 0, configuration: void 0, coerce: void 0, count: void 0, default: void 0, envPrefix: void 0, narg: void 0, normalize: void 0, string: void 0, number: void 0, __: void 0, key: void 0 }, options); const args = tokenizeArgString(argsInput); const inputIsString = typeof argsInput === "string"; const aliases = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias)); const configuration = Object.assign({ "boolean-negation": true, "camel-case-expansion": true, "combine-arrays": false, "dot-notation": true, "duplicate-arguments-array": true, "flatten-duplicate-arrays": true, "greedy-arrays": true, "halt-at-non-option": false, "nargs-eats-options": false, "negation-prefix": "no-", "parse-numbers": true, "parse-positional-numbers": true, "populate--": false, "set-placeholder-key": false, "short-option-groups": true, "strip-aliased": false, "strip-dashed": false, "unknown-options-as-args": false }, opts.configuration); const defaults = Object.assign(/* @__PURE__ */ Object.create(null), opts.default); const configObjects = opts.configObjects || []; const envPrefix = opts.envPrefix; const notFlagsOption = configuration["populate--"]; const notFlagsArgv = notFlagsOption ? "--" : "_"; const newAliases = /* @__PURE__ */ Object.create(null); const defaulted = /* @__PURE__ */ Object.create(null); const __ = opts.__ || mixin2.format; const flags = { aliases: /* @__PURE__ */ Object.create(null), arrays: /* @__PURE__ */ Object.create(null), bools: /* @__PURE__ */ Object.create(null), strings: /* @__PURE__ */ Object.create(null), numbers: /* @__PURE__ */ Object.create(null), counts: /* @__PURE__ */ Object.create(null), normalize: /* @__PURE__ */ Object.create(null), configs: /* @__PURE__ */ Object.create(null), nargs: /* @__PURE__ */ Object.create(null), coercions: /* @__PURE__ */ Object.create(null), keys: [] }; const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)"); [].concat(opts.array || []).filter(Boolean).forEach(function(opt) { const key = typeof opt === "object" ? opt.key : opt; const assignment = Object.keys(opt).map(function(key2) { const arrayFlagKeys = { boolean: "bools", string: "strings", number: "numbers" }; return arrayFlagKeys[key2]; }).filter(Boolean).pop(); if (assignment) { flags[assignment][key] = true; } flags.arrays[key] = true; flags.keys.push(key); }); [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) { flags.bools[key] = true; flags.keys.push(key); }); [].concat(opts.string || []).filter(Boolean).forEach(function(key) { flags.strings[key] = true; flags.keys.push(key); }); [].concat(opts.number || []).filter(Boolean).forEach(function(key) { flags.numbers[key] = true; flags.keys.push(key); }); [].concat(opts.count || []).filter(Boolean).forEach(function(key) { flags.counts[key] = true; flags.keys.push(key); }); [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) { flags.normalize[key] = true; flags.keys.push(key); }); if (typeof opts.narg === "object") { Object.entries(opts.narg).forEach(([key, value]) => { if (typeof value === "number") { flags.nargs[key] = value; flags.keys.push(key); } }); } if (typeof opts.coerce === "object") { Object.entries(opts.coerce).forEach(([key, value]) => { if (typeof value === "function") { flags.coercions[key] = value; flags.keys.push(key); } }); } if (typeof opts.config !== "undefined") { if (Array.isArray(opts.config) || typeof opts.config === "string") { ; [].concat(opts.config).filter(Boolean).forEach(function(key) { flags.configs[key] = true; }); } else if (typeof opts.config === "object") { Object.entries(opts.config).forEach(([key, value]) => { if (typeof value === "boolean" || typeof value === "function") { flags.configs[key] = value; } }); } } extendAliases(opts.key, aliases, opts.default, flags.arrays); Object.keys(defaults).forEach(function(key) { (flags.aliases[key] || []).forEach(function(alias) { defaults[alias] = defaults[key]; }); }); let error = null; checkConfiguration(); let notFlags = []; const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] }); const argvReturn = {}; for (let i = 0; i < args.length; i++) { const arg = args[i]; const truncatedArg = arg.replace(/^-{3,}/, "---"); let broken; let key; let letters; let m; let next; let value; if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { pushPositional(arg); } else if (truncatedArg.match(/^---+(=|$)/)) { pushPositional(arg); continue; } else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) { m = arg.match(/^--?([^=]+)=([\s\S]*)$/); if (m !== null && Array.isArray(m) && m.length >= 3) { if (checkAllAliases(m[1], flags.arrays)) { i = eatArray(i, m[1], args, m[2]); } else if (checkAllAliases(m[1], flags.nargs) !== false) { i = eatNargs(i, m[1], args, m[2]); } else { setArg(m[1], m[2], true); } } } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) { m = arg.match(negatedBoolean); if (m !== null && Array.isArray(m) && m.length >= 2) { key = m[1]; setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); } } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) { m = arg.match(/^--?(.+)/); if (m !== null && Array.isArray(m) && m.length >= 2) { key = m[1]; if (checkAllAliases(key, flags.arrays)) { i = eatArray(i, key, args); } else if (checkAllAliases(key, flags.nargs) !== false) { i = eatNargs(i, key, args); } else { next = args[i + 1]; if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) { setArg(key, next); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next); i++; } else { setArg(key, defaultValue(key)); } } } } else if (arg.match(/^-.\..+=/)) { m = arg.match(/^-([^=]+)=([\s\S]*)$/); if (m !== null && Array.isArray(m) && m.length >= 3) { setArg(m[1], m[2]); } } else if (arg.match(/^-.\..+/) && !arg.match(negative)) { next = args[i + 1]; m = arg.match(/^-(.\..+)/); if (m !== null && Array.isArray(m) && m.length >= 2) { key = m[1]; if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) { setArg(key, next); i++; } else { setArg(key, defaultValue(key)); } } } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { letters = arg.slice(1, -1).split(""); broken = false; for (let j = 0; j < letters.length; j++) { next = arg.slice(j + 2); if (letters[j + 1] && letters[j + 1] === "=") { value = arg.slice(j + 3); key = letters[j]; if (checkAllAliases(key, flags.arrays)) { i = eatArray(i, key, args, value); } else if (checkAllAliases(key, flags.nargs) !== false) { i = eatNargs(i, key, args, value); } else { setArg(key, value); } broken = true; break; } if (next === "-") { setArg(letters[j], next); continue; } if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) { setArg(letters[j], next); broken = true; break; } if (letters[j + 1] && letters[j + 1].match(/\W/)) { setArg(letters[j], next); broken = true; break; } else { setArg(letters[j], defaultValue(letters[j])); } } key = arg.slice(-1)[0]; if (!broken && key !== "-") { if (checkAllAliases(key, flags.arrays)) { i = eatArray(i, key, args); } else if (checkAllAliases(key, flags.nargs) !== false) { i = eatNargs(i, key, args); } else { next = args[i + 1]; if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) { setArg(key, next); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next); i++; } else { setArg(key, defaultValue(key)); } } } } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) { key = arg.slice(1); setArg(key, defaultValue(key)); } else if (arg === "--") { notFlags = args.slice(i + 1); break; } else if (configuration["halt-at-non-option"]) { notFlags = args.slice(i); break; } else { pushPositional(arg); } } applyEnvVars(argv, true); applyEnvVars(argv, false); setConfig(argv); setConfigObjects(); applyDefaultsAndAliases(argv, flags.aliases, defaults, true); applyCoercions(argv); if (configuration["set-placeholder-key"]) setPlaceholderKeys(argv); Object.keys(flags.counts).forEach(function(key) { if (!hasKey(argv, key.split("."))) setArg(key, 0); }); if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = []; notFlags.forEach(function(key) { argv[notFlagsArgv].push(key); }); if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) { Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => { delete argv[key]; }); } if (configuration["strip-aliased"]) { ; [].concat(...Object.keys(aliases).map((k) => aliases[k])).forEach((alias) => { if (configuration["camel-case-expansion"] && alias.includes("-")) { delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")]; } delete argv[alias]; }); } function pushPositional(arg) { const maybeCoercedNumber = maybeCoerceNumber("_", arg); if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") { argv._.push(maybeCoercedNumber); } } function eatNargs(i, key, args2, argAfterEqualSign) { let ii; let toEat = checkAllAliases(key, flags.nargs); toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat; if (toEat === 0) { if (!isUndefined(argAfterEqualSign)) { error = Error(__("Argument unexpected for: %s", key)); } setArg(key, defaultValue(key)); return i; } let available = isUndefined(argAfterEqualSign) ? 0 : 1; if (configuration["nargs-eats-options"]) { if (args2.length - (i + 1) + available < toEat) { error = Error(__("Not enough arguments following: %s", key)); } available = toEat; } else { for (ii = i + 1; ii < args2.length; ii++) { if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii])) available++; else break; } if (available < toEat) error = Error(__("Not enough arguments following: %s", key)); } let consumed = Math.min(available, toEat); if (!isUndefined(argAfterEqualSign) && consumed > 0) { setArg(key, argAfterEqualSign); consumed--; } for (ii = i + 1; ii < consumed + i + 1; ii++) { setArg(key, args2[ii]); } return i + consumed; } function eatArray(i, key, args2, argAfterEqualSign) { let argsToSet = []; let next = argAfterEqualSign || args2[i + 1]; const nargsCount = checkAllAliases(key, flags.nargs); if (checkAllAliases(key, flags.bools) && !/^(true|false)$/.test(next)) { argsToSet.push(true); } else if (isUndefined(next) || isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) { if (defaults[key] !== void 0) { const defVal = defaults[key]; argsToSet = Array.isArray(defVal) ? defVal : [defVal]; } } else { if (!isUndefined(argAfterEqualSign)) { argsToSet.push(processValue(key, argAfterEqualSign, true)); } for (let ii = i + 1; ii < args2.length; ii++) { if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount) break; next = args2[ii]; if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) break; i = ii; argsToSet.push(processValue(key, next, inputIsString)); } } if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) { error = Error(__("Not enough arguments following: %s", key)); } setArg(key, argsToSet); return i; } function setArg(key, val, shouldStripQuotes = inputIsString) { if (/-/.test(key) && configuration["camel-case-expansion"]) { const alias = key.split(".").map(function(prop) { return camelCase(prop); }).join("."); addNewAlias(key, alias); } const value = processValue(key, val, shouldStripQuotes); const splitKey = key.split("."); setKey(argv, splitKey, value); if (flags.aliases[key]) { flags.aliases[key].forEach(function(x) { const keyProperties = x.split("."); setKey(argv, keyProperties, value); }); } if (splitKey.length > 1 && configuration["dot-notation"]) { ; (flags.aliases[splitKey[0]] || []).forEach(function(x) { let keyProperties = x.split("."); const a = [].concat(splitKey); a.shift(); keyProperties = keyProperties.concat(a); if (!(flags.aliases[key] || []).includes(keyProperties.join("."))) { setKey(argv, keyProperties, value); } }); } if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { const keys = [key].concat(flags.aliases[key] || []); keys.forEach(function(key2) { Object.defineProperty(argvReturn, key2, { enumerable: true, get() { return val; }, set(value2) { val = typeof value2 === "string" ? mixin2.normalize(value2) : value2; } }); }); } } function addNewAlias(key, alias) { if (!(flags.aliases[key] && flags.aliases[key].length)) { flags.aliases[key] = [alias]; newAliases[alias] = true; } if (!(flags.aliases[alias] && flags.aliases[alias].length)) { addNewAlias(alias, key); } } function processValue(key, val, shouldStripQuotes) { if (shouldStripQuotes) { val = stripQuotes(val); } if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { if (typeof val === "string") val = val === "true"; } let value = Array.isArray(val) ? val.map(function(v) { return maybeCoerceNumber(key, v); }) : maybeCoerceNumber(key, val); if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === "boolean")) { value = increment(); } if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { if (Array.isArray(val)) value = val.map((val2) => { return mixin2.normalize(val2); }); else value = mixin2.normalize(val); } return value; } function maybeCoerceNumber(key, value) { if (!configuration["parse-positional-numbers"] && key === "_") return value; if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`))); if (shouldCoerceNumber || !isUndefined(value) && checkAllAliases(key, flags.numbers)) { value = Number(value); } } return value; } function setConfig(argv2) { const configLookup = /* @__PURE__ */ Object.create(null); applyDefaultsAndAliases(configLookup, flags.aliases, defaults); Object.keys(flags.configs).forEach(function(configKey) { const configPath = argv2[configKey] || configLookup[configKey]; if (configPath) { try { let config = null; const resolvedConfigPath = mixin2.resolve(mixin2.cwd(), configPath); const resolveConfig = flags.configs[configKey]; if (typeof resolveConfig === "function") { try { config = resolveConfig(resolvedConfigPath); } catch (e) { config = e; } if (config instanceof Error) { error = config; return; } } else { config = mixin2.require(resolvedConfigPath); } setConfigObject(config); } catch (ex) { if (ex.name === "PermissionDenied") error = ex; else if (argv2[configKey]) error = Error(__("Invalid JSON config file: %s", configPath)); } } }); } function setConfigObject(config, prev) { Object.keys(config).forEach(function(key) { const value = config[key]; const fullKey = prev ? prev + "." + key : key; if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) { setConfigObject(value, fullKey); } else { if (!hasKey(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags.arrays) && configuration["combine-arrays"]) { setArg(fullKey, value); } } }); } function setConfigObjects() { if (typeof configObjects !== "undefined") { configObjects.forEach(function(configObject) { setConfigObject(configObject); }); } } function applyEnvVars(argv2, configOnly) { if (typeof envPrefix === "undefined") return; const prefix = typeof envPrefix === "string" ? envPrefix : ""; const env2 = mixin2.env(); Object.keys(env2).forEach(function(envVar) { if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) { const keys = envVar.split("__").map(function(key, i) { if (i === 0) { key = key.substring(prefix.length); } return camelCase(key); }); if ((configOnly && flags.configs[keys.join(".")] || !configOnly) && !hasKey(argv2, keys)) { setArg(keys.join("."), env2[envVar]); } } }); } function applyCoercions(argv2) { let coerce; const applied = /* @__PURE__ */ new Set(); Object.keys(argv2).forEach(function(key) { if (!applied.has(key)) { coerce = checkAllAliases(key, flags.coercions); if (typeof coerce === "function") { try { const value = maybeCoerceNumber(key, coerce(argv2[key])); [].concat(flags.aliases[key] || [], key).forEach((ali) => { applied.add(ali); argv2[ali] = value; }); } catch (err) { error = err; } } } }); } function setPlaceholderKeys(argv2) { flags.keys.forEach((key) => { if (~key.indexOf(".")) return; if (typeof argv2[key] === "undefined") argv2[key] = void 0; }); return argv2; } function applyDefaultsAndAliases(obj, aliases2, defaults2, canLog = false) { Object.keys(defaults2).forEach(function(key) { if (!hasKey(obj, key.split("."))) { setKey(obj, key.split("."), defaults2[key]); if (canLog) defaulted[key] = true; (aliases2[key] || []).forEach(function(x) { if (hasKey(obj, x.split("."))) return; setKey(obj, x.split("."), defaults2[key]); }); } }); } function hasKey(obj, keys) { let o = obj; if (!configuration["dot-notation"]) keys = [keys.join(".")]; keys.slice(0, -1).forEach(function(key2) { o = o[key2] || {}; }); const key = keys[keys.length - 1]; if (typeof o !== "object") return false; else return key in o; } function setKey(obj, keys, value) { let o = obj; if (!configuration["dot-notation"]) keys = [keys.join(".")]; keys.slice(0, -1).forEach(function(key2) { key2 = sanitizeKey(key2); if (typeof o === "object" && o[key2] === void 0) { o[key2] = {}; } if (typeof o[key2] !== "object" || Array.isArray(o[key2])) { if (Array.isArray(o[key2])) { o[key2].push({}); } else { o[key2] = [o[key2], {}]; } o = o[key2][o[key2].length - 1]; } else { o = o[key2]; } }); const key = sanitizeKey(keys[keys.length - 1]); const isTypeArray = checkAllAliases(keys.join("."), flags.arrays); const isValueArray = Array.isArray(value); let duplicate = configuration["duplicate-arguments-array"]; if (!duplicate && checkAllAliases(key, flags.nargs)) { duplicate = true; if (!isUndefined(o[key]) && flags.nargs[key] === 1 || Array.isArray(o[key]) && o[key].length === flags.nargs[key]) { o[key] = void 0; } } if (value === increment()) { o[key] = increment(o[key]); } else if (Array.isArray(o[key])) { if (duplicate && isTypeArray && isValueArray) { o[key] = configuration["flatten-duplicate-arrays"] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { o[key] = value; } else { o[key] = o[key].concat([value]); } } else if (o[key] === void 0 && isTypeArray) { o[key] = isValueArray ? value : [value]; } else if (duplicate && !(o[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) { o[key] = [o[key], value]; } else { o[key] = value; } } function extendAliases(...args2) { args2.forEach(function(obj) { Object.keys(obj || {}).forEach(function(key) { if (flags.aliases[key]) return; flags.aliases[key] = [].concat(aliases[key] || []); flags.aliases[key].concat(key).forEach(function(x) { if (/-/.test(x) && configuration["camel-case-expansion"]) { const c = camelCase(x); if (c !== key && flags.aliases[key].indexOf(c) === -1) { flags.aliases[key].push(c); newAliases[c] = true; } } }); flags.aliases[key].concat(key).forEach(function(x) { if (x.length > 1 && /[A-Z]/.test(x) && configuration["camel-case-expansion"]) { const c = decamelize(x, "-"); if (c !== key && flags.aliases[key].indexOf(c) === -1) { flags.aliases[key].push(c); newAliases[c] = true; } } }); flags.aliases[key].forEach(function(x) { flags.aliases[x] = [key].concat(flags.aliases[key].filter(function(y) { return x !== y; })); }); }); }); } function checkAllAliases(key, flag) { const toCheck = [].concat(flags.aliases[key] || [], key); const keys = Object.keys(flag); const setAlias = toCheck.find((key2) => keys.includes(key2)); return setAlias ? flag[setAlias] : false; } function hasAnyFlag(key) { const flagsKeys = Object.keys(flags); const toCheck = [].concat(flagsKeys.map((k) => flags[k])); return toCheck.some(function(flag) { return Array.isArray(flag) ? flag.includes(key) : flag[key]; }); } function hasFlagsMatching(ar