cli.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const tty = require("tty");
  8. const webpackSchema = require("../schemas/WebpackOptions.json");
  9. /** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */
  10. /** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
  11. /** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
  12. /** @typedef {JSONSchema4 | JSONSchema6 | JSONSchema7} JSONSchema */
  13. /** @typedef {JSONSchema & { absolutePath: boolean, instanceof: string, cli: { helper?: boolean, exclude?: boolean, description?: string, negatedDescription?: string, resetDescription?: string } }} Schema */
  14. // TODO add originPath to PathItem for better errors
  15. /**
  16. * Defines the path item type used by this module.
  17. * @typedef {object} PathItem
  18. * @property {Schema} schema the part of the schema
  19. * @property {string} path the path in the config
  20. */
  21. /** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */
  22. /** @typedef {string | number | boolean | RegExp} Value */
  23. /**
  24. * Defines the problem type used by this module.
  25. * @typedef {object} Problem
  26. * @property {ProblemType} type
  27. * @property {string} path
  28. * @property {string} argument
  29. * @property {Value=} value
  30. * @property {number=} index
  31. * @property {string=} expected
  32. */
  33. /**
  34. * Defines the local problem type used by this module.
  35. * @typedef {object} LocalProblem
  36. * @property {ProblemType} type
  37. * @property {string} path
  38. * @property {string=} expected
  39. */
  40. /** @typedef {{ [key: string]: EnumValue }} EnumValueObject */
  41. /** @typedef {EnumValue[]} EnumValueArray */
  42. /** @typedef {string | number | boolean | EnumValueObject | EnumValueArray | null} EnumValue */
  43. /**
  44. * Defines the argument config type used by this module.
  45. * @typedef {object} ArgumentConfig
  46. * @property {string=} description
  47. * @property {string=} negatedDescription
  48. * @property {string} path
  49. * @property {boolean} multiple
  50. * @property {"enum" | "string" | "path" | "number" | "boolean" | "RegExp" | "reset"} type
  51. * @property {EnumValue[]=} values
  52. */
  53. /** @typedef {"string" | "number" | "boolean"} SimpleType */
  54. /**
  55. * Defines the argument type used by this module.
  56. * @typedef {object} Argument
  57. * @property {string | undefined} description
  58. * @property {SimpleType} simpleType
  59. * @property {boolean} multiple
  60. * @property {ArgumentConfig[]} configs
  61. */
  62. /** @typedef {Record<string, Argument>} Flags */
  63. /** @typedef {Record<string, EXPECTED_ANY>} ObjectConfiguration */
  64. /**
  65. * Returns object of arguments.
  66. * @param {Schema=} schema a json schema to create arguments for (by default webpack schema is used)
  67. * @returns {Flags} object of arguments
  68. */
  69. const getArguments = (schema = webpackSchema) => {
  70. /** @type {Flags} */
  71. const flags = {};
  72. /**
  73. * Path to argument name.
  74. * @param {string} input input
  75. * @returns {string} result
  76. */
  77. const pathToArgumentName = (input) =>
  78. input
  79. .replace(/\./g, "-")
  80. .replace(/\[\]/g, "")
  81. .replace(
  82. /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu,
  83. "$1-$2"
  84. )
  85. .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-")
  86. .toLowerCase();
  87. /**
  88. * Returns schema part.
  89. * @param {string} path path
  90. * @returns {Schema} schema part
  91. */
  92. const getSchemaPart = (path) => {
  93. const newPath = path.split("/");
  94. let schemaPart = schema;
  95. for (let i = 1; i < newPath.length; i++) {
  96. const inner = schemaPart[/** @type {keyof Schema} */ (newPath[i])];
  97. if (!inner) {
  98. break;
  99. }
  100. schemaPart = inner;
  101. }
  102. return schemaPart;
  103. };
  104. /**
  105. * Returns description.
  106. * @param {PathItem[]} path path in the schema
  107. * @returns {string | undefined} description
  108. */
  109. const getDescription = (path) => {
  110. for (const { schema } of path) {
  111. if (schema.cli) {
  112. if (schema.cli.helper) continue;
  113. if (schema.cli.description) return schema.cli.description;
  114. }
  115. if (schema.description) return schema.description;
  116. }
  117. };
  118. /**
  119. * Gets negated description.
  120. * @param {PathItem[]} path path in the schema
  121. * @returns {string | undefined} negative description
  122. */
  123. const getNegatedDescription = (path) => {
  124. for (const { schema } of path) {
  125. if (schema.cli) {
  126. if (schema.cli.helper) continue;
  127. if (schema.cli.negatedDescription) return schema.cli.negatedDescription;
  128. }
  129. }
  130. };
  131. /**
  132. * Gets reset description.
  133. * @param {PathItem[]} path path in the schema
  134. * @returns {string | undefined} reset description
  135. */
  136. const getResetDescription = (path) => {
  137. for (const { schema } of path) {
  138. if (schema.cli) {
  139. if (schema.cli.helper) continue;
  140. if (schema.cli.resetDescription) return schema.cli.resetDescription;
  141. }
  142. }
  143. };
  144. /**
  145. * Schema to argument config.
  146. * @param {Schema} schemaPart schema
  147. * @returns {Pick<ArgumentConfig, "type" | "values"> | undefined} partial argument config
  148. */
  149. const schemaToArgumentConfig = (schemaPart) => {
  150. if (schemaPart.enum) {
  151. return {
  152. type: "enum",
  153. values: schemaPart.enum
  154. };
  155. }
  156. switch (schemaPart.type) {
  157. case "number":
  158. return {
  159. type: "number"
  160. };
  161. case "string":
  162. return {
  163. type: schemaPart.absolutePath ? "path" : "string"
  164. };
  165. case "boolean":
  166. return {
  167. type: "boolean"
  168. };
  169. }
  170. if (schemaPart.instanceof === "RegExp") {
  171. return {
  172. type: "RegExp"
  173. };
  174. }
  175. return undefined;
  176. };
  177. /**
  178. * Adds the provided path to this object.
  179. * @param {PathItem[]} path path in the schema
  180. * @returns {void}
  181. */
  182. const addResetFlag = (path) => {
  183. const schemaPath = path[0].path;
  184. const name = pathToArgumentName(`${schemaPath}.reset`);
  185. const description =
  186. getResetDescription(path) ||
  187. `Clear all items provided in '${schemaPath}' configuration. ${getDescription(
  188. path
  189. )}`;
  190. flags[name] = {
  191. configs: [
  192. {
  193. type: "reset",
  194. multiple: false,
  195. description,
  196. path: schemaPath
  197. }
  198. ],
  199. description: undefined,
  200. simpleType:
  201. /** @type {SimpleType} */
  202. (/** @type {unknown} */ (undefined)),
  203. multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined))
  204. };
  205. };
  206. /**
  207. * Adds the provided path to this object.
  208. * @param {PathItem[]} path full path in schema
  209. * @param {boolean} multiple inside of an array
  210. * @returns {number} number of arguments added
  211. */
  212. const addFlag = (path, multiple) => {
  213. const argConfigBase = schemaToArgumentConfig(path[0].schema);
  214. if (!argConfigBase) return 0;
  215. const negatedDescription = getNegatedDescription(path);
  216. const name = pathToArgumentName(path[0].path);
  217. /** @type {ArgumentConfig} */
  218. const argConfig = {
  219. ...argConfigBase,
  220. multiple,
  221. description: getDescription(path),
  222. path: path[0].path
  223. };
  224. if (negatedDescription) {
  225. argConfig.negatedDescription = negatedDescription;
  226. }
  227. if (!flags[name]) {
  228. flags[name] = {
  229. configs: [],
  230. description: undefined,
  231. simpleType:
  232. /** @type {SimpleType} */
  233. (/** @type {unknown} */ (undefined)),
  234. multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined))
  235. };
  236. }
  237. if (
  238. flags[name].configs.some(
  239. (item) => JSON.stringify(item) === JSON.stringify(argConfig)
  240. )
  241. ) {
  242. return 0;
  243. }
  244. if (
  245. flags[name].configs.some(
  246. (item) => item.type === argConfig.type && item.multiple !== multiple
  247. )
  248. ) {
  249. if (multiple) {
  250. throw new Error(
  251. `Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)`
  252. );
  253. }
  254. return 0;
  255. }
  256. flags[name].configs.push(argConfig);
  257. return 1;
  258. };
  259. // TODO support `not` and `if/then/else`
  260. // TODO support `const`, but we don't use it on our schema
  261. /**
  262. * Returns added arguments.
  263. * @param {Schema} schemaPart the current schema
  264. * @param {string} schemaPath the current path in the schema
  265. * @param {PathItem[]} path all previous visited schemaParts
  266. * @param {string | null} inArray if inside of an array, the path to the array
  267. * @returns {number} added arguments
  268. */
  269. const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => {
  270. while (schemaPart.$ref) {
  271. schemaPart = getSchemaPart(schemaPart.$ref);
  272. }
  273. const repetitions = path.filter(({ schema }) => schema === schemaPart);
  274. if (
  275. repetitions.length >= 2 ||
  276. repetitions.some(({ path }) => path === schemaPath)
  277. ) {
  278. return 0;
  279. }
  280. if (schemaPart.cli && schemaPart.cli.exclude) return 0;
  281. /** @type {PathItem[]} */
  282. const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path];
  283. let addedArguments = 0;
  284. addedArguments += addFlag(fullPath, Boolean(inArray));
  285. if (schemaPart.type === "object") {
  286. if (schemaPart.properties) {
  287. for (const property of Object.keys(schemaPart.properties)) {
  288. addedArguments += traverse(
  289. /** @type {Schema} */
  290. (schemaPart.properties[property]),
  291. schemaPath ? `${schemaPath}.${property}` : property,
  292. fullPath,
  293. inArray
  294. );
  295. }
  296. }
  297. return addedArguments;
  298. }
  299. if (schemaPart.type === "array") {
  300. if (inArray) {
  301. return 0;
  302. }
  303. if (Array.isArray(schemaPart.items)) {
  304. const i = 0;
  305. for (const item of schemaPart.items) {
  306. addedArguments += traverse(
  307. /** @type {Schema} */
  308. (item),
  309. `${schemaPath}.${i}`,
  310. fullPath,
  311. schemaPath
  312. );
  313. }
  314. return addedArguments;
  315. }
  316. addedArguments += traverse(
  317. /** @type {Schema} */
  318. (schemaPart.items),
  319. `${schemaPath}[]`,
  320. fullPath,
  321. schemaPath
  322. );
  323. if (addedArguments > 0) {
  324. addResetFlag(fullPath);
  325. addedArguments++;
  326. }
  327. return addedArguments;
  328. }
  329. const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf;
  330. if (maybeOf) {
  331. const items = maybeOf;
  332. for (let i = 0; i < items.length; i++) {
  333. addedArguments += traverse(
  334. /** @type {Schema} */
  335. (items[i]),
  336. schemaPath,
  337. fullPath,
  338. inArray
  339. );
  340. }
  341. return addedArguments;
  342. }
  343. return addedArguments;
  344. };
  345. traverse(schema);
  346. // Summarize flags
  347. for (const name of Object.keys(flags)) {
  348. /** @type {Argument} */
  349. const argument = flags[name];
  350. argument.description = argument.configs.reduce((desc, { description }) => {
  351. if (!desc) return description;
  352. if (!description) return desc;
  353. if (desc.includes(description)) return desc;
  354. return `${desc} ${description}`;
  355. }, /** @type {string | undefined} */ (undefined));
  356. argument.simpleType =
  357. /** @type {SimpleType} */
  358. (
  359. argument.configs.reduce((t, argConfig) => {
  360. /** @type {SimpleType} */
  361. let type = "string";
  362. switch (argConfig.type) {
  363. case "number":
  364. type = "number";
  365. break;
  366. case "reset":
  367. case "boolean":
  368. type = "boolean";
  369. break;
  370. case "enum": {
  371. const values =
  372. /** @type {NonNullable<ArgumentConfig["values"]>} */
  373. (argConfig.values);
  374. if (values.every((v) => typeof v === "boolean")) type = "boolean";
  375. if (values.every((v) => typeof v === "number")) type = "number";
  376. break;
  377. }
  378. }
  379. if (t === undefined) return type;
  380. return t === type ? t : "string";
  381. }, /** @type {SimpleType | undefined} */ (undefined))
  382. );
  383. argument.multiple = argument.configs.some((c) => c.multiple);
  384. }
  385. return flags;
  386. };
  387. /** @type {WeakMap<EXPECTED_OBJECT, number>} */
  388. const cliAddedItems = new WeakMap();
  389. /** @typedef {string | number} Property */
  390. /**
  391. * Gets object and property.
  392. * @param {ObjectConfiguration} config configuration
  393. * @param {string} schemaPath path in the config
  394. * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
  395. * @returns {{ problem?: LocalProblem, object?: ObjectConfiguration, property?: Property, value?: EXPECTED_OBJECT | EXPECTED_ANY[] }} problem or object with property and value
  396. */
  397. const getObjectAndProperty = (config, schemaPath, index = 0) => {
  398. if (!schemaPath) return { value: config };
  399. const parts = schemaPath.split(".");
  400. const property = /** @type {string} */ (parts.pop());
  401. let current = config;
  402. let i = 0;
  403. for (const part of parts) {
  404. const isArray = part.endsWith("[]");
  405. const name = isArray ? part.slice(0, -2) : part;
  406. let value = current[name];
  407. if (isArray) {
  408. if (value === undefined) {
  409. value = {};
  410. current[name] = [...Array.from({ length: index }), value];
  411. cliAddedItems.set(current[name], index + 1);
  412. } else if (!Array.isArray(value)) {
  413. return {
  414. problem: {
  415. type: "unexpected-non-array-in-path",
  416. path: parts.slice(0, i).join(".")
  417. }
  418. };
  419. } else {
  420. let addedItems = cliAddedItems.get(value) || 0;
  421. while (addedItems <= index) {
  422. value.push(undefined);
  423. addedItems++;
  424. }
  425. cliAddedItems.set(value, addedItems);
  426. const x = value.length - addedItems + index;
  427. if (value[x] === undefined) {
  428. value[x] = {};
  429. } else if (value[x] === null || typeof value[x] !== "object") {
  430. return {
  431. problem: {
  432. type: "unexpected-non-object-in-path",
  433. path: parts.slice(0, i).join(".")
  434. }
  435. };
  436. }
  437. value = value[x];
  438. }
  439. } else if (value === undefined) {
  440. value = current[name] = {};
  441. } else if (value === null || typeof value !== "object") {
  442. return {
  443. problem: {
  444. type: "unexpected-non-object-in-path",
  445. path: parts.slice(0, i).join(".")
  446. }
  447. };
  448. }
  449. current = value;
  450. i++;
  451. }
  452. const value = current[property];
  453. if (property.endsWith("[]")) {
  454. const name = property.slice(0, -2);
  455. const value = current[name];
  456. if (value === undefined) {
  457. current[name] = [...Array.from({ length: index }), undefined];
  458. cliAddedItems.set(current[name], index + 1);
  459. return { object: current[name], property: index, value: undefined };
  460. } else if (!Array.isArray(value)) {
  461. current[name] = [value, ...Array.from({ length: index }), undefined];
  462. cliAddedItems.set(current[name], index + 1);
  463. return { object: current[name], property: index + 1, value: undefined };
  464. }
  465. let addedItems = cliAddedItems.get(value) || 0;
  466. while (addedItems <= index) {
  467. value.push(undefined);
  468. addedItems++;
  469. }
  470. cliAddedItems.set(value, addedItems);
  471. const x = value.length - addedItems + index;
  472. if (value[x] === undefined) {
  473. value[x] = {};
  474. } else if (value[x] === null || typeof value[x] !== "object") {
  475. return {
  476. problem: {
  477. type: "unexpected-non-object-in-path",
  478. path: schemaPath
  479. }
  480. };
  481. }
  482. return {
  483. object: value,
  484. property: x,
  485. value: value[x]
  486. };
  487. }
  488. return { object: current, property, value };
  489. };
  490. /**
  491. * Updates value using the provided config.
  492. * @param {ObjectConfiguration} config configuration
  493. * @param {string} schemaPath path in the config
  494. * @param {ParsedValue} value parsed value
  495. * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined
  496. * @returns {LocalProblem | null} problem or null for success
  497. */
  498. const setValue = (config, schemaPath, value, index) => {
  499. const { problem, object, property } = getObjectAndProperty(
  500. config,
  501. schemaPath,
  502. index
  503. );
  504. if (problem) return problem;
  505. /** @type {ObjectConfiguration} */
  506. (object)[/** @type {Property} */ (property)] = value;
  507. return null;
  508. };
  509. /**
  510. * Process argument config.
  511. * @param {ArgumentConfig} argConfig processing instructions
  512. * @param {ObjectConfiguration} config configuration
  513. * @param {Value} value the value
  514. * @param {number | undefined} index the index if multiple values provided
  515. * @returns {LocalProblem | null} a problem if any
  516. */
  517. const processArgumentConfig = (argConfig, config, value, index) => {
  518. if (index !== undefined && !argConfig.multiple) {
  519. return {
  520. type: "multiple-values-unexpected",
  521. path: argConfig.path
  522. };
  523. }
  524. const parsed = parseValueForArgumentConfig(argConfig, value);
  525. if (parsed === undefined) {
  526. return {
  527. type: "invalid-value",
  528. path: argConfig.path,
  529. expected: getExpectedValue(argConfig)
  530. };
  531. }
  532. const problem = setValue(config, argConfig.path, parsed, index);
  533. if (problem) return problem;
  534. return null;
  535. };
  536. /**
  537. * Gets expected value.
  538. * @param {ArgumentConfig} argConfig processing instructions
  539. * @returns {string | undefined} expected message
  540. */
  541. const getExpectedValue = (argConfig) => {
  542. switch (argConfig.type) {
  543. case "boolean":
  544. return "true | false";
  545. case "RegExp":
  546. return "regular expression (example: /ab?c*/)";
  547. case "enum":
  548. return /** @type {NonNullable<ArgumentConfig["values"]>} */ (
  549. argConfig.values
  550. )
  551. .map((v) => `${v}`)
  552. .join(" | ");
  553. case "reset":
  554. return "true (will reset the previous value to an empty array)";
  555. default:
  556. return argConfig.type;
  557. }
  558. };
  559. /** @typedef {null | string | number | boolean | RegExp | EnumValue | []} ParsedValue */
  560. const DECIMAL_NUMBER_REGEXP = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
  561. /**
  562. * Parses value for argument config.
  563. * @param {ArgumentConfig} argConfig processing instructions
  564. * @param {Value} value the value
  565. * @returns {ParsedValue | undefined} parsed value
  566. */
  567. const parseValueForArgumentConfig = (argConfig, value) => {
  568. switch (argConfig.type) {
  569. case "string":
  570. if (typeof value === "string") {
  571. return value;
  572. }
  573. break;
  574. case "path":
  575. if (typeof value === "string") {
  576. return path.resolve(value);
  577. }
  578. break;
  579. case "number":
  580. if (typeof value === "number") return value;
  581. if (typeof value === "string" && DECIMAL_NUMBER_REGEXP.test(value)) {
  582. const n = Number(value);
  583. if (!Number.isNaN(n)) return n;
  584. }
  585. break;
  586. case "boolean":
  587. if (typeof value === "boolean") return value;
  588. if (value === "true") return true;
  589. if (value === "false") return false;
  590. break;
  591. case "RegExp":
  592. if (value instanceof RegExp) return value;
  593. if (typeof value === "string") {
  594. // cspell:word yugi
  595. const match = /^\/(.*)\/([yugi]*)$/.exec(value);
  596. if (match && !/[^\\]\//.test(match[1])) {
  597. return new RegExp(match[1], match[2]);
  598. }
  599. }
  600. break;
  601. case "enum": {
  602. const values =
  603. /** @type {EnumValue[]} */
  604. (argConfig.values);
  605. if (values.includes(/** @type {Exclude<Value, RegExp>} */ (value))) {
  606. return value;
  607. }
  608. for (const item of values) {
  609. if (`${item}` === value) return item;
  610. }
  611. break;
  612. }
  613. case "reset":
  614. if (value === true) return [];
  615. break;
  616. }
  617. };
  618. /** @typedef {Record<string, Value[]>} Values */
  619. /**
  620. * Processes the provided arg.
  621. * @param {Flags} args object of arguments
  622. * @param {ObjectConfiguration} config configuration
  623. * @param {Values} values object with values
  624. * @returns {Problem[] | null} problems or null for success
  625. */
  626. const processArguments = (args, config, values) => {
  627. /** @type {Problem[]} */
  628. const problems = [];
  629. for (const key of Object.keys(values)) {
  630. const arg = args[key];
  631. if (!arg) {
  632. problems.push({
  633. type: "unknown-argument",
  634. path: "",
  635. argument: key
  636. });
  637. continue;
  638. }
  639. /**
  640. * Processes the provided value.
  641. * @param {Value} value value
  642. * @param {number | undefined} i index
  643. */
  644. const processValue = (value, i) => {
  645. /** @type {Problem[]} */
  646. const currentProblems = [];
  647. for (const argConfig of arg.configs) {
  648. const problem = processArgumentConfig(argConfig, config, value, i);
  649. if (!problem) {
  650. return;
  651. }
  652. currentProblems.push({
  653. ...problem,
  654. argument: key,
  655. value,
  656. index: i
  657. });
  658. }
  659. problems.push(...currentProblems);
  660. };
  661. const value = values[key];
  662. if (Array.isArray(value)) {
  663. for (let i = 0; i < value.length; i++) {
  664. processValue(value[i], i);
  665. }
  666. } else {
  667. processValue(value, undefined);
  668. }
  669. }
  670. if (problems.length === 0) return null;
  671. return problems;
  672. };
  673. /**
  674. * Checks whether this object is color supported.
  675. * @returns {boolean} true when colors supported, otherwise false
  676. */
  677. const isColorSupported = () => {
  678. const { env = {}, argv = [], platform = "" } = process;
  679. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  680. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  681. const isWindows = platform === "win32";
  682. const isDumbTerminal = env.TERM === "dumb";
  683. const isCompatibleTerminal = tty.isatty(1) && env.TERM && !isDumbTerminal;
  684. const isCI =
  685. "CI" in env &&
  686. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  687. return (
  688. !isDisabled &&
  689. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI)
  690. );
  691. };
  692. /**
  693. * Returns result.
  694. * @param {number} index index
  695. * @param {string} string string
  696. * @param {string} close close
  697. * @param {string=} replace replace
  698. * @param {string=} head head
  699. * @param {string=} tail tail
  700. * @param {number=} next next
  701. * @returns {string} result
  702. */
  703. const replaceClose = (
  704. index,
  705. string,
  706. close,
  707. replace,
  708. head = string.slice(0, Math.max(0, index)) + replace,
  709. tail = string.slice(Math.max(0, index + close.length)),
  710. next = tail.indexOf(close)
  711. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  712. /**
  713. * Returns result.
  714. * @param {number} index index to replace
  715. * @param {string} string string
  716. * @param {string} open open string
  717. * @param {string} close close string
  718. * @param {string=} replace extra replace
  719. * @returns {string} result
  720. */
  721. const clearBleed = (index, string, open, close, replace) =>
  722. index < 0
  723. ? open + string + close
  724. : open + replaceClose(index, string, close, replace) + close;
  725. /** @typedef {(value: EXPECTED_ANY) => string} PrintFunction */
  726. /**
  727. * Returns function to create color.
  728. * @param {string} open open string
  729. * @param {string} close close string
  730. * @param {string=} replace extra replace
  731. * @param {number=} at at
  732. * @returns {PrintFunction} function to create color
  733. */
  734. const filterEmpty =
  735. (open, close, replace = open, at = open.length + 1) =>
  736. (string) =>
  737. string || !(string === "" || string === undefined)
  738. ? clearBleed(`${string}`.indexOf(close, at), string, open, close, replace)
  739. : "";
  740. /**
  741. * Returns result.
  742. * @param {number} open open code
  743. * @param {number} close close code
  744. * @param {string=} replace extra replace
  745. * @returns {PrintFunction} result
  746. */
  747. const init = (open, close, replace) =>
  748. filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace);
  749. /**
  750. * Defines the colors type used by this module.
  751. * @typedef {{ reset: PrintFunction, bold: PrintFunction, dim: PrintFunction, italic: PrintFunction, underline: PrintFunction, inverse: PrintFunction, hidden: PrintFunction, strikethrough: PrintFunction, black: PrintFunction, red: PrintFunction, green: PrintFunction, yellow: PrintFunction, blue: PrintFunction, magenta: PrintFunction, cyan: PrintFunction, white: PrintFunction, gray: PrintFunction, bgBlack: PrintFunction, bgRed: PrintFunction, bgGreen: PrintFunction, bgYellow: PrintFunction, bgBlue: PrintFunction, bgMagenta: PrintFunction, bgCyan: PrintFunction, bgWhite: PrintFunction, blackBright: PrintFunction, redBright: PrintFunction, greenBright: PrintFunction, yellowBright: PrintFunction, blueBright: PrintFunction, magentaBright: PrintFunction, cyanBright: PrintFunction, whiteBright: PrintFunction, bgBlackBright: PrintFunction, bgRedBright: PrintFunction, bgGreenBright: PrintFunction, bgYellowBright: PrintFunction, bgBlueBright: PrintFunction, bgMagentaBright: PrintFunction, bgCyanBright: PrintFunction, bgWhiteBright: PrintFunction }} Colors
  752. */
  753. /**
  754. * Defines the colors options type used by this module.
  755. * @typedef {object} ColorsOptions
  756. * @property {boolean=} useColor force use colors
  757. */
  758. /**
  759. * Creates a colors from the provided colors option.
  760. * @param {ColorsOptions=} options options
  761. * @returns {Colors} colors
  762. */
  763. const createColors = ({ useColor = isColorSupported() } = {}) => ({
  764. reset: useColor ? init(0, 0) : String,
  765. bold: useColor ? init(1, 22, "\u001B[22m\u001B[1m") : String,
  766. dim: useColor ? init(2, 22, "\u001B[22m\u001B[2m") : String,
  767. italic: useColor ? init(3, 23) : String,
  768. underline: useColor ? init(4, 24) : String,
  769. inverse: useColor ? init(7, 27) : String,
  770. hidden: useColor ? init(8, 28) : String,
  771. strikethrough: useColor ? init(9, 29) : String,
  772. black: useColor ? init(30, 39) : String,
  773. red: useColor ? init(31, 39) : String,
  774. green: useColor ? init(32, 39) : String,
  775. yellow: useColor ? init(33, 39) : String,
  776. blue: useColor ? init(34, 39) : String,
  777. magenta: useColor ? init(35, 39) : String,
  778. cyan: useColor ? init(36, 39) : String,
  779. white: useColor ? init(37, 39) : String,
  780. gray: useColor ? init(90, 39) : String,
  781. bgBlack: useColor ? init(40, 49) : String,
  782. bgRed: useColor ? init(41, 49) : String,
  783. bgGreen: useColor ? init(42, 49) : String,
  784. bgYellow: useColor ? init(43, 49) : String,
  785. bgBlue: useColor ? init(44, 49) : String,
  786. bgMagenta: useColor ? init(45, 49) : String,
  787. bgCyan: useColor ? init(46, 49) : String,
  788. bgWhite: useColor ? init(47, 49) : String,
  789. blackBright: useColor ? init(90, 39) : String,
  790. redBright: useColor ? init(91, 39) : String,
  791. greenBright: useColor ? init(92, 39) : String,
  792. yellowBright: useColor ? init(93, 39) : String,
  793. blueBright: useColor ? init(94, 39) : String,
  794. magentaBright: useColor ? init(95, 39) : String,
  795. cyanBright: useColor ? init(96, 39) : String,
  796. whiteBright: useColor ? init(97, 39) : String,
  797. bgBlackBright: useColor ? init(100, 49) : String,
  798. bgRedBright: useColor ? init(101, 49) : String,
  799. bgGreenBright: useColor ? init(102, 49) : String,
  800. bgYellowBright: useColor ? init(103, 49) : String,
  801. bgBlueBright: useColor ? init(104, 49) : String,
  802. bgMagentaBright: useColor ? init(105, 49) : String,
  803. bgCyanBright: useColor ? init(106, 49) : String,
  804. bgWhiteBright: useColor ? init(107, 49) : String
  805. });
  806. module.exports.createColors = createColors;
  807. module.exports.getArguments = getArguments;
  808. module.exports.isColorSupported = isColorSupported;
  809. module.exports.processArguments = processArguments;