index.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. var __create = Object.create;
  2. var __defProp = Object.defineProperty;
  3. var __defProps = Object.defineProperties;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  6. var __getOwnPropNames = Object.getOwnPropertyNames;
  7. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  8. var __getProtoOf = Object.getPrototypeOf;
  9. var __hasOwnProp = Object.prototype.hasOwnProperty;
  10. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  11. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  12. var __spreadValues = (a, b) => {
  13. for (var prop in b || (b = {}))
  14. if (__hasOwnProp.call(b, prop))
  15. __defNormalProp(a, prop, b[prop]);
  16. if (__getOwnPropSymbols)
  17. for (var prop of __getOwnPropSymbols(b)) {
  18. if (__propIsEnum.call(b, prop))
  19. __defNormalProp(a, prop, b[prop]);
  20. }
  21. return a;
  22. };
  23. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  24. var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
  25. var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  26. get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  27. }) : x)(function(x) {
  28. if (typeof require !== "undefined")
  29. return require.apply(this, arguments);
  30. throw new Error('Dynamic require of "' + x + '" is not supported');
  31. });
  32. var __reExport = (target, module, copyDefault, desc) => {
  33. if (module && typeof module === "object" || typeof module === "function") {
  34. for (let key of __getOwnPropNames(module))
  35. if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
  36. __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable });
  37. }
  38. return target;
  39. };
  40. var __toESM = (module, isNodeMode) => {
  41. return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", !isNodeMode && module && module.__esModule ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module);
  42. };
  43. // src/listr.ts
  44. import pMap from "p-map";
  45. import { Subject as Subject2 } from "rxjs";
  46. // src/constants/state.constants.ts
  47. var ListrTaskState = /* @__PURE__ */ ((ListrTaskState2) => {
  48. ListrTaskState2["PENDING"] = "PENDING";
  49. ListrTaskState2["COMPLETED"] = "COMPLETED";
  50. ListrTaskState2["FAILED"] = "FAILED";
  51. ListrTaskState2["SKIPPED"] = "SKIPPED";
  52. ListrTaskState2["ROLLING_BACK"] = "ROLLING_BACK";
  53. ListrTaskState2["ROLLED_BACK"] = "ROLLED_BACK";
  54. ListrTaskState2["RETRY"] = "RETRY";
  55. return ListrTaskState2;
  56. })(ListrTaskState || {});
  57. // src/lib/task.ts
  58. import { Observable, Subject } from "rxjs";
  59. import { Readable } from "stream";
  60. // src/constants/event.constants.ts
  61. var ListrEventType = /* @__PURE__ */ ((ListrEventType2) => {
  62. ListrEventType2["TITLE"] = "TITLE";
  63. ListrEventType2["STATE"] = "STATE";
  64. ListrEventType2["ENABLED"] = "ENABLED";
  65. ListrEventType2["SUBTASK"] = "SUBTASK";
  66. ListrEventType2["DATA"] = "DATA";
  67. ListrEventType2["MESSAGE"] = "MESSAGE";
  68. return ListrEventType2;
  69. })(ListrEventType || {});
  70. // src/utils/general.ts
  71. import rfdc from "rfdc";
  72. var clone = rfdc({ circles: true });
  73. function cloneObject(obj) {
  74. return clone(obj);
  75. }
  76. // src/interfaces/listr-error.interface.ts
  77. var ListrError = class extends Error {
  78. constructor(error, type, task) {
  79. super(error.message);
  80. this.error = error;
  81. this.type = type;
  82. this.task = task;
  83. var _a2;
  84. this.name = "ListrError";
  85. this.path = [...(_a2 = task.listr.path) != null ? _a2 : [], task.title].join(" > ");
  86. if ((task == null ? void 0 : task.options.collectErrors) === "full") {
  87. this.task = cloneObject(task);
  88. this.ctx = cloneObject(task.listr.ctx);
  89. }
  90. this.stack = error == null ? void 0 : error.stack;
  91. }
  92. };
  93. var ListrErrorTypes = /* @__PURE__ */ ((ListrErrorTypes2) => {
  94. ListrErrorTypes2["WILL_RETRY"] = "WILL_RETRY";
  95. ListrErrorTypes2["WILL_ROLLBACK"] = "WILL_ROLLBACK";
  96. ListrErrorTypes2["HAS_FAILED_TO_ROLLBACK"] = "HAS_FAILED_TO_ROLLBACK";
  97. ListrErrorTypes2["HAS_FAILED"] = "HAS_FAILED";
  98. ListrErrorTypes2["HAS_FAILED_WITHOUT_ERROR"] = "HAS_FAILED_WITHOUT_ERROR";
  99. return ListrErrorTypes2;
  100. })(ListrErrorTypes || {});
  101. var PromptError = class extends Error {
  102. constructor(message) {
  103. super(message);
  104. this.name = "PromptError";
  105. }
  106. };
  107. // src/utils/assert.ts
  108. function assertFunctionOrSelf(functionOrSelf, ...args) {
  109. if (typeof functionOrSelf === "function") {
  110. return functionOrSelf(...args);
  111. } else {
  112. return functionOrSelf;
  113. }
  114. }
  115. // src/renderer/default.renderer.ts
  116. import cliTruncate from "cli-truncate";
  117. import logUpdate from "log-update";
  118. import { EOL } from "os";
  119. import cliWrap from "wrap-ansi";
  120. // src/utils/colorette.ts
  121. import { createColors } from "colorette";
  122. var _a;
  123. var colorette_default = createColors({ useColor: ((_a = process.env) == null ? void 0 : _a.LISTR_DISABLE_COLOR) !== "1" });
  124. // src/utils/is-unicode-supported.ts
  125. function isUnicodeSupported() {
  126. if (process.platform !== "win32") {
  127. return true;
  128. }
  129. return Boolean(process.env.CI) || Boolean(process.env.WT_SESSION) || process.env.TERM_PROGRAM === "vscode" || process.env.TERM === "xterm-256color" || process.env.TERM === "alacritty";
  130. }
  131. // src/utils/figures.ts
  132. var FIGURES_MAIN = {
  133. warning: "\u26A0",
  134. cross: "\u2716",
  135. arrowDown: "\u2193",
  136. tick: "\u2714",
  137. arrowRight: "\u2192",
  138. pointer: "\u276F",
  139. checkboxOn: "\u2612",
  140. arrowLeft: "\u2190",
  141. squareSmallFilled: "\u25FC",
  142. pointerSmall: "\u203A"
  143. };
  144. var FIGURES_FALLBACK = __spreadProps(__spreadValues({}, FIGURES_MAIN), {
  145. warning: "\u203C",
  146. cross: "\xD7",
  147. tick: "\u221A",
  148. pointer: ">",
  149. checkboxOn: "[\xD7]",
  150. squareSmallFilled: "\u25A0"
  151. });
  152. var figures = isUnicodeSupported() ? FIGURES_MAIN : FIGURES_FALLBACK;
  153. // src/utils/indent-string.ts
  154. function indentString(string, count) {
  155. return string.replace(/^(?!\s*$)/gm, " ".repeat(count));
  156. }
  157. // src/utils/parse-time.ts
  158. function parseTaskTime(duration) {
  159. const seconds = Math.floor(duration / 1e3);
  160. const minutes = Math.floor(seconds / 60);
  161. let parsedTime;
  162. if (seconds === 0 && minutes === 0) {
  163. parsedTime = `0.${Math.floor(duration / 100)}s`;
  164. }
  165. if (seconds > 0) {
  166. parsedTime = `${seconds % 60}s`;
  167. }
  168. if (minutes > 0) {
  169. parsedTime = `${minutes}m${parsedTime}`;
  170. }
  171. return parsedTime;
  172. }
  173. // src/renderer/default.renderer.ts
  174. var _DefaultRenderer = class {
  175. constructor(tasks, options, renderHook$) {
  176. this.tasks = tasks;
  177. this.options = options;
  178. this.renderHook$ = renderHook$;
  179. this.bottomBar = {};
  180. this.spinner = !isUnicodeSupported() ? ["-", "\\", "|", "/"] : ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
  181. this.spinnerPosition = 0;
  182. this.options = __spreadValues(__spreadValues({}, _DefaultRenderer.rendererOptions), this.options);
  183. }
  184. getTaskOptions(task) {
  185. return __spreadValues(__spreadValues({}, _DefaultRenderer.rendererTaskOptions), task.rendererTaskOptions);
  186. }
  187. isBottomBar(task) {
  188. const bottomBar = this.getTaskOptions(task).bottomBar;
  189. return typeof bottomBar === "number" && bottomBar !== 0 || typeof bottomBar === "boolean" && bottomBar !== false;
  190. }
  191. hasPersistentOutput(task) {
  192. return this.getTaskOptions(task).persistentOutput === true;
  193. }
  194. hasTimer(task) {
  195. return this.getTaskOptions(task).showTimer === true;
  196. }
  197. getSelfOrParentOption(task, key) {
  198. var _a2, _b, _c;
  199. return (_c = (_a2 = task == null ? void 0 : task.rendererOptions) == null ? void 0 : _a2[key]) != null ? _c : (_b = this.options) == null ? void 0 : _b[key];
  200. }
  201. getTaskTime(task) {
  202. return colorette_default.dim(`[${parseTaskTime(task.message.duration)}]`);
  203. }
  204. createRender(options) {
  205. options = __spreadValues(__spreadValues({}, {
  206. tasks: true,
  207. bottomBar: true,
  208. prompt: true
  209. }), options);
  210. const render = [];
  211. const renderTasks = this.multiLineRenderer(this.tasks);
  212. const renderBottomBar = this.renderBottomBar();
  213. const renderPrompt = this.renderPrompt();
  214. if (options.tasks && (renderTasks == null ? void 0 : renderTasks.trim().length) > 0) {
  215. render.push(renderTasks);
  216. }
  217. if (options.bottomBar && (renderBottomBar == null ? void 0 : renderBottomBar.trim().length) > 0) {
  218. render.push((render.length > 0 ? EOL : "") + renderBottomBar);
  219. }
  220. if (options.prompt && (renderPrompt == null ? void 0 : renderPrompt.trim().length) > 0) {
  221. render.push((render.length > 0 ? EOL : "") + renderPrompt);
  222. }
  223. return render.length > 0 ? render.join(EOL) : "";
  224. }
  225. render() {
  226. var _a2;
  227. if (this.id) {
  228. return;
  229. }
  230. const updateRender = () => logUpdate(this.createRender());
  231. if (!((_a2 = this.options) == null ? void 0 : _a2.lazy)) {
  232. this.id = setInterval(() => {
  233. this.spinnerPosition = ++this.spinnerPosition % this.spinner.length;
  234. updateRender();
  235. }, 100);
  236. }
  237. this.renderHook$.subscribe(() => {
  238. updateRender();
  239. });
  240. }
  241. end() {
  242. clearInterval(this.id);
  243. if (this.id) {
  244. this.id = void 0;
  245. }
  246. logUpdate.clear();
  247. logUpdate.done();
  248. if (!this.options.clearOutput) {
  249. process.stdout.write(this.createRender({ prompt: false }) + EOL);
  250. }
  251. }
  252. multiLineRenderer(tasks, level = 0) {
  253. var _a2, _b;
  254. let output = [];
  255. for (const task of tasks) {
  256. if (task.isEnabled()) {
  257. if (task.hasTitle()) {
  258. if (!(tasks.some((task2) => task2.hasFailed()) && !task.hasFailed() && task.options.exitOnError !== false && !(task.isCompleted() || task.isSkipped()))) {
  259. if (task.hasFailed() && this.getSelfOrParentOption(task, "collapseErrors")) {
  260. output = [
  261. ...output,
  262. this.formatString(!task.hasSubtasks() && task.message.error && this.getSelfOrParentOption(task, "showErrorMessage") ? task.message.error : task.title, this.getSymbol(task), level)
  263. ];
  264. } else if (task.isSkipped() && this.getSelfOrParentOption(task, "collapseSkips")) {
  265. output = [
  266. ...output,
  267. this.formatString(this.addSuffixToMessage(task.message.skip && this.getSelfOrParentOption(task, "showSkipMessage") ? task.message.skip : task.title, "SKIPPED", this.getSelfOrParentOption(task, "suffixSkips")), this.getSymbol(task), level)
  268. ];
  269. } else if (task.isRetrying() && this.getSelfOrParentOption(task, "suffixRetries")) {
  270. output = [...output, this.formatString(this.addSuffixToMessage(task.title, `RETRYING-${task.message.retry.count}`), this.getSymbol(task), level)];
  271. } else if (task.isCompleted() && task.hasTitle() && (this.getSelfOrParentOption(task, "showTimer") || this.hasTimer(task))) {
  272. output = [...output, this.formatString(`${task == null ? void 0 : task.title} ${this.getTaskTime(task)}`, this.getSymbol(task), level)];
  273. } else {
  274. output = [...output, this.formatString(task.title, this.getSymbol(task), level)];
  275. }
  276. } else {
  277. output = [...output, this.formatString(task.title, colorette_default.red(figures.squareSmallFilled), level)];
  278. }
  279. }
  280. if (!task.hasSubtasks() || !this.getSelfOrParentOption(task, "showSubtasks")) {
  281. if (task.hasFailed() && this.getSelfOrParentOption(task, "collapseErrors") === false && (this.getSelfOrParentOption(task, "showErrorMessage") || !this.getSelfOrParentOption(task, "showSubtasks"))) {
  282. output = [...output, this.dumpData(task, level, "error")];
  283. } else if (task.isSkipped() && this.getSelfOrParentOption(task, "collapseSkips") === false && (this.getSelfOrParentOption(task, "showSkipMessage") || !this.getSelfOrParentOption(task, "showSubtasks"))) {
  284. output = [...output, this.dumpData(task, level, "skip")];
  285. }
  286. }
  287. if (task == null ? void 0 : task.output) {
  288. if ((task.isPending() || task.isRetrying() || task.isRollingBack()) && task.isPrompt()) {
  289. this.promptBar = task.output;
  290. } else if (this.isBottomBar(task) || !task.hasTitle()) {
  291. const data = [this.dumpData(task, -1)];
  292. if (!this.bottomBar[task.id]) {
  293. this.bottomBar[task.id] = {};
  294. this.bottomBar[task.id].data = [];
  295. const bottomBar = this.getTaskOptions(task).bottomBar;
  296. if (typeof bottomBar === "boolean") {
  297. this.bottomBar[task.id].items = 1;
  298. } else {
  299. this.bottomBar[task.id].items = bottomBar;
  300. }
  301. }
  302. if (!((_b = (_a2 = this.bottomBar[task.id]) == null ? void 0 : _a2.data) == null ? void 0 : _b.some((element) => data.includes(element))) && !task.isSkipped()) {
  303. this.bottomBar[task.id].data = [...this.bottomBar[task.id].data, ...data];
  304. }
  305. } else if (task.isPending() || task.isRetrying() || task.isRollingBack() || this.hasPersistentOutput(task)) {
  306. output = [...output, this.dumpData(task, level)];
  307. }
  308. }
  309. if (this.getSelfOrParentOption(task, "showSubtasks") !== false && task.hasSubtasks() && (task.isPending() || task.hasFailed() || task.isCompleted() && !task.hasTitle() || task.isCompleted() && this.getSelfOrParentOption(task, "collapse") === false && !task.subtasks.some((subtask) => subtask.rendererOptions.collapse === true) || task.subtasks.some((subtask) => subtask.rendererOptions.collapse === false) || task.subtasks.some((subtask) => subtask.hasFailed()) || task.subtasks.some((subtask) => subtask.hasRolledBack()))) {
  310. const subtaskLevel = !task.hasTitle() ? level : level + 1;
  311. const subtaskRender = this.multiLineRenderer(task.subtasks, subtaskLevel);
  312. if ((subtaskRender == null ? void 0 : subtaskRender.trim()) !== "" && !task.subtasks.every((subtask) => !subtask.hasTitle())) {
  313. output = [...output, subtaskRender];
  314. }
  315. }
  316. if (task.isCompleted() || task.hasFailed() || task.isSkipped() || task.hasRolledBack()) {
  317. this.promptBar = null;
  318. if (!this.hasPersistentOutput(task)) {
  319. delete this.bottomBar[task.id];
  320. }
  321. }
  322. }
  323. }
  324. output = output.filter(Boolean);
  325. if (output.length > 0) {
  326. return output.join(EOL);
  327. } else {
  328. return;
  329. }
  330. }
  331. renderBottomBar() {
  332. if (Object.keys(this.bottomBar).length > 0) {
  333. this.bottomBar = Object.keys(this.bottomBar).reduce((o, key) => {
  334. if (!(o == null ? void 0 : o[key])) {
  335. o[key] = {};
  336. }
  337. o[key] = this.bottomBar[key];
  338. this.bottomBar[key].data = this.bottomBar[key].data.slice(-this.bottomBar[key].items);
  339. o[key].data = this.bottomBar[key].data;
  340. return o;
  341. }, {});
  342. return Object.values(this.bottomBar).reduce((o, value) => o = [...o, ...value.data], []).filter(Boolean).join(EOL);
  343. }
  344. }
  345. renderPrompt() {
  346. if (this.promptBar) {
  347. return this.promptBar;
  348. }
  349. }
  350. dumpData(task, level, source = "output") {
  351. let data;
  352. switch (source) {
  353. case "output":
  354. data = task.output;
  355. break;
  356. case "skip":
  357. data = task.message.skip;
  358. break;
  359. case "error":
  360. data = task.message.error;
  361. break;
  362. }
  363. if (task.hasTitle() && source === "error" && data === task.title) {
  364. return;
  365. }
  366. if (typeof data === "string") {
  367. return this.formatString(data, this.getSymbol(task, true), level + 1);
  368. }
  369. }
  370. formatString(str, icon, level) {
  371. if (str.trim() === "") {
  372. return;
  373. }
  374. str = `${icon} ${str}`;
  375. let parsedStr;
  376. let columns = process.stdout.columns ? process.stdout.columns : 80;
  377. columns = columns - level * this.options.indentation - 2;
  378. switch (this.options.formatOutput) {
  379. case "truncate":
  380. parsedStr = str.split(EOL).map((s, i) => {
  381. return cliTruncate(this.indentMultilineOutput(s, i), columns);
  382. });
  383. break;
  384. case "wrap":
  385. parsedStr = cliWrap(str, columns, { hard: true }).split(EOL).map((s, i) => this.indentMultilineOutput(s, i));
  386. break;
  387. default:
  388. throw new Error("Format option for the renderer is wrong.");
  389. }
  390. if (this.options.removeEmptyLines) {
  391. parsedStr = parsedStr.filter(Boolean);
  392. }
  393. return indentString(parsedStr.join(EOL), level * this.options.indentation);
  394. }
  395. indentMultilineOutput(str, i) {
  396. return i > 0 ? indentString(str.trim(), 2) : str.trim();
  397. }
  398. getSymbol(task, data = false) {
  399. var _a2, _b, _c;
  400. if (task.isPending() && !data) {
  401. return ((_a2 = this.options) == null ? void 0 : _a2.lazy) || this.getSelfOrParentOption(task, "showSubtasks") !== false && task.hasSubtasks() && !task.subtasks.every((subtask) => !subtask.hasTitle()) ? colorette_default.yellow(figures.pointer) : colorette_default.yellowBright(this.spinner[this.spinnerPosition]);
  402. } else if (task.isCompleted() && !data) {
  403. return task.hasSubtasks() && task.subtasks.some((subtask) => subtask.hasFailed()) ? colorette_default.yellow(figures.warning) : colorette_default.green(figures.tick);
  404. } else if (task.isRetrying() && !data) {
  405. return ((_b = this.options) == null ? void 0 : _b.lazy) ? colorette_default.yellow(figures.warning) : colorette_default.yellow(this.spinner[this.spinnerPosition]);
  406. } else if (task.isRollingBack() && !data) {
  407. return ((_c = this.options) == null ? void 0 : _c.lazy) ? colorette_default.red(figures.warning) : colorette_default.red(this.spinner[this.spinnerPosition]);
  408. } else if (task.hasRolledBack() && !data) {
  409. return colorette_default.red(figures.arrowLeft);
  410. } else if (task.hasFailed() && !data) {
  411. return task.hasSubtasks() ? colorette_default.red(figures.pointer) : colorette_default.red(figures.cross);
  412. } else if (task.isSkipped() && !data && this.getSelfOrParentOption(task, "collapseSkips") === false) {
  413. return colorette_default.yellow(figures.warning);
  414. } else if (task.isSkipped() && (data || this.getSelfOrParentOption(task, "collapseSkips"))) {
  415. return colorette_default.yellow(figures.arrowDown);
  416. }
  417. return !data ? colorette_default.dim(figures.squareSmallFilled) : figures.pointerSmall;
  418. }
  419. addSuffixToMessage(message, suffix, condition) {
  420. return (condition != null ? condition : true) ? message + colorette_default.dim(` [${suffix}]`) : message;
  421. }
  422. };
  423. var DefaultRenderer = _DefaultRenderer;
  424. DefaultRenderer.nonTTY = false;
  425. DefaultRenderer.rendererOptions = {
  426. indentation: 2,
  427. clearOutput: false,
  428. showSubtasks: true,
  429. collapse: true,
  430. collapseSkips: true,
  431. showSkipMessage: true,
  432. suffixSkips: true,
  433. collapseErrors: true,
  434. showErrorMessage: true,
  435. suffixRetries: true,
  436. lazy: false,
  437. showTimer: false,
  438. removeEmptyLines: true,
  439. formatOutput: "truncate"
  440. };
  441. // src/renderer/silent.renderer.ts
  442. var SilentRenderer = class {
  443. constructor(tasks, options) {
  444. this.tasks = tasks;
  445. this.options = options;
  446. }
  447. render() {
  448. }
  449. end() {
  450. }
  451. };
  452. SilentRenderer.nonTTY = true;
  453. // src/renderer/simple.renderer.ts
  454. import { stderr as logUpdate2 } from "log-update";
  455. import { EOL as EOL2 } from "os";
  456. var _SimpleRenderer = class {
  457. constructor(tasks, options) {
  458. this.tasks = tasks;
  459. this.options = options;
  460. this.eventTypeRendererMap = {
  461. ["SUBTASK" /* SUBTASK */]: (task) => {
  462. if (task.hasTitle()) {
  463. this.log(`${colorette_default.blue(figures.pointer)} ${task.title}`);
  464. }
  465. if (task.hasSubtasks()) {
  466. this.render(task.subtasks);
  467. }
  468. },
  469. ["STATE" /* STATE */]: (task) => {
  470. if (task.isCompleted() && task.hasTitle()) {
  471. this.log(`${colorette_default.green(figures.tick)} ${task.title}`);
  472. }
  473. },
  474. ["DATA" /* DATA */]: (task, event) => {
  475. if (task.isPrompt() && !String(event.data).match(/^\n$/)) {
  476. logUpdate2(`${event.data}`);
  477. } else {
  478. this.log(`${figures.pointerSmall} ${event.data}`);
  479. }
  480. },
  481. ["MESSAGE" /* MESSAGE */]: (task, event) => {
  482. if (event.data.error) {
  483. const title = _SimpleRenderer.formatTitle(task);
  484. this.log(`${colorette_default.red(figures.cross)}${title}: ${event.data.error}`);
  485. } else if (event.data.skip) {
  486. const title = _SimpleRenderer.formatTitle(task);
  487. const skip = task.title !== event.data.skip ? `: ${event.data.skip}` : "";
  488. this.log(`${colorette_default.yellow(figures.arrowDown)}${title} [${colorette_default.yellow(`skipped${skip}`)}]`);
  489. } else if (event.data.rollback) {
  490. const title = _SimpleRenderer.formatTitle(task);
  491. this.log(`${colorette_default.red(figures.arrowLeft)}${title}: ${event.data.rollback}`);
  492. } else if (event.data.retry) {
  493. const title = _SimpleRenderer.formatTitle(task);
  494. this.log(`[${colorette_default.yellow(`${event.data.retry.count}`)}]${title}`);
  495. }
  496. }
  497. };
  498. this.options = __spreadValues(__spreadValues({}, _SimpleRenderer.rendererOptions), options);
  499. }
  500. static now() {
  501. return new Date();
  502. }
  503. static formatTitle(task) {
  504. return (task == null ? void 0 : task.title) ? ` ${task.title}` : "";
  505. }
  506. log(output) {
  507. const logOut = (msg) => {
  508. process[this.options.output].write(msg.endsWith(EOL2) ? msg : `${msg}${EOL2}`);
  509. };
  510. if (!this.options.prefixWithTimestamp) {
  511. logOut(`${output}`);
  512. return;
  513. }
  514. const now = _SimpleRenderer.now();
  515. const timestamp = String(now.getHours()).padStart(2, "0") + ":" + String(now.getMinutes()).padStart(2, "0") + ":" + String(now.getSeconds()).padStart(2, "0");
  516. logOut(`${colorette_default.dim(`[${timestamp}]`)} ${output}`);
  517. }
  518. end() {
  519. }
  520. render(tasks) {
  521. if (tasks == null ? void 0 : tasks.length) {
  522. tasks.forEach((task) => {
  523. task.subscribe((event) => {
  524. var _a2, _b;
  525. (_b = (_a2 = this.eventTypeRendererMap)[event.type]) == null ? void 0 : _b.call(_a2, task, event);
  526. }, this.log);
  527. });
  528. } else {
  529. this.render(this.tasks);
  530. }
  531. }
  532. };
  533. var SimpleRenderer = _SimpleRenderer;
  534. SimpleRenderer.nonTTY = true;
  535. SimpleRenderer.rendererOptions = { prefixWithTimestamp: false, output: "stdout" };
  536. // src/utils/logger.constants.ts
  537. var LogLevels = /* @__PURE__ */ ((LogLevels2) => {
  538. LogLevels2["SILENT"] = "SILENT";
  539. LogLevels2["FAILED"] = "FAILED";
  540. LogLevels2["SKIPPED"] = "SKIPPED";
  541. LogLevels2["SUCCESS"] = "SUCCESS";
  542. LogLevels2["DATA"] = "DATA";
  543. LogLevels2["STARTED"] = "STARTED";
  544. LogLevels2["TITLE"] = "TITLE";
  545. LogLevels2["RETRY"] = "RETRY";
  546. LogLevels2["ROLLBACK"] = "ROLLBACK";
  547. return LogLevels2;
  548. })(LogLevels || {});
  549. // src/utils/logger.ts
  550. var Logger = class {
  551. constructor(options) {
  552. this.options = options;
  553. }
  554. fail(message) {
  555. message = this.parseMessage("FAILED" /* FAILED */, message);
  556. console.error(message);
  557. }
  558. skip(message) {
  559. message = this.parseMessage("SKIPPED" /* SKIPPED */, message);
  560. console.info(message);
  561. }
  562. success(message) {
  563. message = this.parseMessage("SUCCESS" /* SUCCESS */, message);
  564. console.log(message);
  565. }
  566. data(message) {
  567. message = this.parseMessage("DATA" /* DATA */, message);
  568. console.info(message);
  569. }
  570. start(message) {
  571. message = this.parseMessage("STARTED" /* STARTED */, message);
  572. console.log(message);
  573. }
  574. title(message) {
  575. message = this.parseMessage("TITLE" /* TITLE */, message);
  576. console.info(message);
  577. }
  578. retry(message) {
  579. message = this.parseMessage("RETRY" /* RETRY */, message);
  580. console.warn(message);
  581. }
  582. rollback(message) {
  583. message = this.parseMessage("ROLLBACK" /* ROLLBACK */, message);
  584. console.warn(message);
  585. }
  586. parseMessage(level, message) {
  587. let multiLineMessage;
  588. try {
  589. multiLineMessage = message.split("\n");
  590. } catch {
  591. multiLineMessage = [message];
  592. }
  593. multiLineMessage = multiLineMessage.map((msg) => {
  594. return this.logColoring({
  595. level,
  596. message: msg
  597. });
  598. });
  599. message = multiLineMessage.join("\n");
  600. return message;
  601. }
  602. logColoring({ level, message }) {
  603. var _a2, _b, _c, _d, _e, _f, _g, _h;
  604. let icon;
  605. let coloring = (input) => {
  606. return input;
  607. };
  608. switch (level) {
  609. case "FAILED" /* FAILED */:
  610. if ((_a2 = this.options) == null ? void 0 : _a2.useIcons) {
  611. coloring = colorette_default.red;
  612. icon = figures.cross;
  613. } else {
  614. icon = this.wrapInBrackets(level);
  615. }
  616. break;
  617. case "SKIPPED" /* SKIPPED */:
  618. if ((_b = this.options) == null ? void 0 : _b.useIcons) {
  619. coloring = colorette_default.yellow;
  620. icon = figures.arrowDown;
  621. } else {
  622. icon = this.wrapInBrackets(level);
  623. }
  624. break;
  625. case "SUCCESS" /* SUCCESS */:
  626. if ((_c = this.options) == null ? void 0 : _c.useIcons) {
  627. coloring = colorette_default.green;
  628. icon = figures.tick;
  629. } else {
  630. icon = this.wrapInBrackets(level);
  631. }
  632. break;
  633. case "DATA" /* DATA */:
  634. if ((_d = this.options) == null ? void 0 : _d.useIcons) {
  635. icon = figures.arrowRight;
  636. } else {
  637. icon = this.wrapInBrackets(level);
  638. }
  639. break;
  640. case "STARTED" /* STARTED */:
  641. if ((_e = this.options) == null ? void 0 : _e.useIcons) {
  642. icon = figures.pointer;
  643. } else {
  644. icon = this.wrapInBrackets(level);
  645. }
  646. break;
  647. case "TITLE" /* TITLE */:
  648. if ((_f = this.options) == null ? void 0 : _f.useIcons) {
  649. icon = figures.checkboxOn;
  650. } else {
  651. icon = this.wrapInBrackets(level);
  652. }
  653. break;
  654. case "RETRY" /* RETRY */:
  655. if ((_g = this.options) == null ? void 0 : _g.useIcons) {
  656. coloring = colorette_default.yellow;
  657. icon = figures.pointer;
  658. } else {
  659. icon = this.wrapInBrackets(level);
  660. }
  661. break;
  662. case "ROLLBACK" /* ROLLBACK */:
  663. if ((_h = this.options) == null ? void 0 : _h.useIcons) {
  664. coloring = colorette_default.red;
  665. icon = figures.arrowLeft;
  666. } else {
  667. icon = this.wrapInBrackets(level);
  668. }
  669. break;
  670. }
  671. return coloring(`${icon} ${message}`);
  672. }
  673. wrapInBrackets(level) {
  674. return `[${level}]`;
  675. }
  676. };
  677. // src/renderer/verbose.renderer.ts
  678. var _VerboseRenderer = class {
  679. constructor(tasks, options) {
  680. this.tasks = tasks;
  681. this.options = options;
  682. var _a2, _b, _c, _d;
  683. if (((_a2 = this.options) == null ? void 0 : _a2.logger) && ((_b = this.options) == null ? void 0 : _b.options)) {
  684. this.logger = new this.options.logger(this.options.options);
  685. } else if ((_c = this.options) == null ? void 0 : _c.logger) {
  686. this.logger = new this.options.logger();
  687. } else {
  688. this.logger = new Logger({ useIcons: (_d = this.options) == null ? void 0 : _d.useIcons });
  689. }
  690. this.options = __spreadValues(__spreadValues({}, _VerboseRenderer.rendererOptions), this.options);
  691. }
  692. render() {
  693. this.verboseRenderer(this.tasks);
  694. }
  695. end() {
  696. }
  697. verboseRenderer(tasks) {
  698. return tasks == null ? void 0 : tasks.forEach((task) => {
  699. task.subscribe((event) => {
  700. var _a2, _b, _c, _d, _e, _f, _g, _h;
  701. if (task.isEnabled()) {
  702. const taskTitle = task.hasTitle() ? task.title : "Task without title.";
  703. if (event.type === "SUBTASK" /* SUBTASK */ && task.hasSubtasks()) {
  704. this.verboseRenderer(task.subtasks);
  705. } else if (event.type === "STATE" /* STATE */) {
  706. if (((_a2 = this.options) == null ? void 0 : _a2.logEmptyTitle) !== false || task.hasTitle()) {
  707. if (task.isPending()) {
  708. this.logger.start(taskTitle);
  709. } else if (task.isCompleted()) {
  710. this.logger.success(taskTitle + (((_b = this.options) == null ? void 0 : _b.showTimer) && ((_c = task.message) == null ? void 0 : _c.duration) ? ` [${parseTaskTime(task.message.duration)}]` : ""));
  711. }
  712. }
  713. } else if (event.type === "DATA" /* DATA */ && !!event.data) {
  714. this.logger.data(String(event.data));
  715. } else if (event.type === "TITLE" /* TITLE */) {
  716. if (((_d = this.options) == null ? void 0 : _d.logTitleChange) !== false) {
  717. this.logger.title(String(event.data));
  718. }
  719. } else if (event.type === "MESSAGE" /* MESSAGE */) {
  720. if ((_e = event.data) == null ? void 0 : _e.error) {
  721. this.logger.fail(String(event.data.error));
  722. } else if ((_f = event.data) == null ? void 0 : _f.skip) {
  723. this.logger.skip(String(event.data.skip));
  724. } else if ((_g = event.data) == null ? void 0 : _g.rollback) {
  725. this.logger.rollback(String(event.data.rollback));
  726. } else if ((_h = event.data) == null ? void 0 : _h.retry) {
  727. this.logger.retry(`[${event.data.retry.count}] ` + String(taskTitle));
  728. }
  729. }
  730. }
  731. }, (err) => {
  732. this.logger.fail(err);
  733. });
  734. });
  735. }
  736. };
  737. var VerboseRenderer = _VerboseRenderer;
  738. VerboseRenderer.nonTTY = true;
  739. VerboseRenderer.rendererOptions = {
  740. useIcons: false,
  741. logEmptyTitle: true,
  742. logTitleChange: true
  743. };
  744. // src/utils/renderer.ts
  745. var renderers = {
  746. default: DefaultRenderer,
  747. simple: SimpleRenderer,
  748. verbose: VerboseRenderer,
  749. silent: SilentRenderer
  750. };
  751. function isRendererSupported(renderer) {
  752. return process.stdout.isTTY === true || renderer.nonTTY === true;
  753. }
  754. function getRendererClass(renderer) {
  755. if (typeof renderer === "string") {
  756. return renderers[renderer] || renderers.default;
  757. }
  758. return typeof renderer === "function" ? renderer : renderers.default;
  759. }
  760. function getRenderer(renderer, fallbackRenderer, fallbackCondition, silentCondition) {
  761. let returnValue;
  762. let ret = getRendererClass(renderer);
  763. returnValue = { renderer: ret, nonTTY: false };
  764. const evaluateSilent = assertFunctionOrSelf(silentCondition);
  765. const evaluateFallback = assertFunctionOrSelf(fallbackCondition);
  766. if (evaluateSilent) {
  767. ret = getRendererClass("silent");
  768. returnValue = { renderer: ret, nonTTY: true };
  769. } else if (!isRendererSupported(ret) || evaluateFallback) {
  770. ret = getRendererClass(fallbackRenderer);
  771. returnValue = { renderer: ret, nonTTY: true };
  772. }
  773. return returnValue;
  774. }
  775. // src/utils/uuid.ts
  776. function generateUUID() {
  777. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  778. const r = Math.random() * 16 || 0;
  779. const v = c === "x" ? r : r && 3 || 8;
  780. return v.toString(16);
  781. });
  782. }
  783. // src/lib/task.ts
  784. var Task = class extends Subject {
  785. constructor(listr, tasks, options, rendererOptions) {
  786. super();
  787. this.listr = listr;
  788. this.tasks = tasks;
  789. this.options = options;
  790. this.rendererOptions = rendererOptions;
  791. this.message = {};
  792. var _a2, _b, _c, _d, _e, _f;
  793. this.id = generateUUID();
  794. this.title = (_a2 = this.tasks) == null ? void 0 : _a2.title;
  795. this.initialTitle = (_b = this.tasks) == null ? void 0 : _b.title;
  796. this.task = this.tasks.task;
  797. this.skip = (_d = (_c = this.tasks) == null ? void 0 : _c.skip) != null ? _d : false;
  798. this.enabledFn = (_f = (_e = this.tasks) == null ? void 0 : _e.enabled) != null ? _f : true;
  799. this.rendererTaskOptions = this.tasks.options;
  800. this.renderHook$ = this.listr.renderHook$;
  801. this.subscribe(() => {
  802. this.renderHook$.next();
  803. });
  804. }
  805. set state$(state) {
  806. this.state = state;
  807. this.next({
  808. type: "STATE" /* STATE */,
  809. data: state
  810. });
  811. if (this.hasSubtasks() && this.hasFailed()) {
  812. for (const subtask of this.subtasks) {
  813. if (subtask.state === "PENDING" /* PENDING */) {
  814. subtask.state$ = "FAILED" /* FAILED */;
  815. }
  816. }
  817. }
  818. }
  819. set output$(data) {
  820. this.output = data;
  821. this.next({
  822. type: "DATA" /* DATA */,
  823. data
  824. });
  825. }
  826. set message$(data) {
  827. this.message = __spreadValues(__spreadValues({}, this.message), data);
  828. this.next({
  829. type: "MESSAGE" /* MESSAGE */,
  830. data
  831. });
  832. }
  833. set title$(title) {
  834. this.title = title;
  835. this.next({
  836. type: "TITLE" /* TITLE */,
  837. data: title
  838. });
  839. }
  840. async check(ctx) {
  841. if (this.state === void 0) {
  842. this.enabled = await assertFunctionOrSelf(this.enabledFn, ctx);
  843. this.next({
  844. type: "ENABLED" /* ENABLED */,
  845. data: this.enabled
  846. });
  847. }
  848. }
  849. hasSubtasks() {
  850. var _a2;
  851. return ((_a2 = this.subtasks) == null ? void 0 : _a2.length) > 0;
  852. }
  853. isPending() {
  854. return this.state === "PENDING" /* PENDING */;
  855. }
  856. isSkipped() {
  857. return this.state === "SKIPPED" /* SKIPPED */;
  858. }
  859. isCompleted() {
  860. return this.state === "COMPLETED" /* COMPLETED */;
  861. }
  862. hasFailed() {
  863. return this.state === "FAILED" /* FAILED */;
  864. }
  865. isRollingBack() {
  866. return this.state === "ROLLING_BACK" /* ROLLING_BACK */;
  867. }
  868. hasRolledBack() {
  869. return this.state === "ROLLED_BACK" /* ROLLED_BACK */;
  870. }
  871. isRetrying() {
  872. return this.state === "RETRY" /* RETRY */;
  873. }
  874. isEnabled() {
  875. return this.enabled;
  876. }
  877. hasTitle() {
  878. return typeof (this == null ? void 0 : this.title) === "string";
  879. }
  880. isPrompt() {
  881. return !!this.prompt;
  882. }
  883. async run(context, wrapper) {
  884. var _a2, _b, _c, _d, _e;
  885. const handleResult = (result) => {
  886. if (result instanceof Listr) {
  887. result.options = __spreadValues(__spreadValues({}, this.options), result.options);
  888. result.rendererClass = getRenderer("silent").renderer;
  889. result.renderHook$.subscribe(() => {
  890. this.renderHook$.next();
  891. });
  892. this.subtasks = result.tasks;
  893. result.err = this.listr.err;
  894. this.next({ type: "SUBTASK" /* SUBTASK */ });
  895. result = result.run(context);
  896. } else if (this.isPrompt()) {
  897. } else if (result instanceof Promise) {
  898. result = result.then(handleResult);
  899. } else if (result instanceof Readable) {
  900. result = new Promise((resolve, reject) => {
  901. result.on("data", (data) => {
  902. this.output$ = data.toString();
  903. });
  904. result.on("error", (error) => reject(error));
  905. result.on("end", () => resolve(null));
  906. });
  907. } else if (result instanceof Observable) {
  908. result = new Promise((resolve, reject) => {
  909. result.subscribe({
  910. next: (data) => {
  911. this.output$ = data;
  912. },
  913. error: reject,
  914. complete: resolve
  915. });
  916. });
  917. }
  918. return result;
  919. };
  920. const startTime = Date.now();
  921. this.state$ = "PENDING" /* PENDING */;
  922. const skipped = await assertFunctionOrSelf(this.skip, context);
  923. if (skipped) {
  924. if (typeof skipped === "string") {
  925. this.message$ = { skip: skipped };
  926. } else if (this.hasTitle()) {
  927. this.message$ = { skip: this.title };
  928. } else {
  929. this.message$ = { skip: "Skipped task without a title." };
  930. }
  931. this.state$ = "SKIPPED" /* SKIPPED */;
  932. return;
  933. }
  934. try {
  935. const retryCount = ((_a2 = this.tasks) == null ? void 0 : _a2.retry) && ((_b = this.tasks) == null ? void 0 : _b.retry) > 0 ? this.tasks.retry + 1 : 1;
  936. for (let retries = 1; retries <= retryCount; retries++) {
  937. try {
  938. await handleResult(this.task(context, wrapper));
  939. break;
  940. } catch (err) {
  941. if (retries !== retryCount) {
  942. this.retry = { count: retries, withError: err };
  943. this.message$ = { retry: this.retry };
  944. this.title$ = this.initialTitle;
  945. this.output = void 0;
  946. wrapper.report(err, "WILL_RETRY" /* WILL_RETRY */);
  947. this.state$ = "RETRY" /* RETRY */;
  948. } else {
  949. throw err;
  950. }
  951. }
  952. }
  953. if (this.isPending() || this.isRetrying()) {
  954. this.message$ = { duration: Date.now() - startTime };
  955. this.state$ = "COMPLETED" /* COMPLETED */;
  956. }
  957. } catch (error) {
  958. if (this.prompt instanceof PromptError) {
  959. error = new Error(this.prompt.message);
  960. }
  961. if ((_c = this.tasks) == null ? void 0 : _c.rollback) {
  962. wrapper.report(error, "WILL_ROLLBACK" /* WILL_ROLLBACK */);
  963. try {
  964. this.state$ = "ROLLING_BACK" /* ROLLING_BACK */;
  965. await this.tasks.rollback(context, wrapper);
  966. this.state$ = "ROLLED_BACK" /* ROLLED_BACK */;
  967. this.message$ = { rollback: this.title };
  968. } catch (err) {
  969. this.state$ = "FAILED" /* FAILED */;
  970. wrapper.report(err, "HAS_FAILED_TO_ROLLBACK" /* HAS_FAILED_TO_ROLLBACK */);
  971. throw err;
  972. }
  973. if (((_d = this.listr.options) == null ? void 0 : _d.exitAfterRollback) !== false) {
  974. throw new Error(this.title);
  975. }
  976. } else {
  977. this.state$ = "FAILED" /* FAILED */;
  978. if (this.listr.options.exitOnError !== false && await assertFunctionOrSelf((_e = this.tasks) == null ? void 0 : _e.exitOnError, context) !== false) {
  979. wrapper.report(error, "HAS_FAILED" /* HAS_FAILED */);
  980. throw error;
  981. } else if (!this.hasSubtasks()) {
  982. wrapper.report(error, "HAS_FAILED_WITHOUT_ERROR" /* HAS_FAILED_WITHOUT_ERROR */);
  983. }
  984. }
  985. } finally {
  986. this.complete();
  987. }
  988. }
  989. };
  990. // src/lib/task-wrapper.ts
  991. import through from "through";
  992. // src/constants/clearline-regex.constants.ts
  993. var CLEAR_LINE_REGEX = "(?:\\u001b|\\u009b)\\[[\\=><~/#&.:=?%@~_-]*[0-9]*[\\a-ln-tqyz=><~/#&.:=?%@~_-]+";
  994. var BELL_REGEX = /\u0007/;
  995. // src/utils/prompt.ts
  996. function defaultCancelCallback(settings) {
  997. const errorMsg = "Cancelled prompt.";
  998. if (this instanceof TaskWrapper) {
  999. this.task.prompt = new PromptError(errorMsg);
  1000. } else if ((settings == null ? void 0 : settings.error) !== false) {
  1001. throw new Error(errorMsg);
  1002. } else {
  1003. return errorMsg;
  1004. }
  1005. }
  1006. async function createPrompt(options, settings) {
  1007. let cancelCallback;
  1008. if (settings == null ? void 0 : settings.cancelCallback) {
  1009. cancelCallback = settings.cancelCallback;
  1010. } else {
  1011. cancelCallback = defaultCancelCallback;
  1012. }
  1013. if (!Array.isArray(options)) {
  1014. options = [__spreadProps(__spreadValues({}, options), { name: "default" })];
  1015. } else if (options.length === 1) {
  1016. options = options.reduce((o, option) => {
  1017. return [...o, Object.assign(option, { name: "default" })];
  1018. }, []);
  1019. }
  1020. options = options.reduce((o, option) => {
  1021. var _a2;
  1022. return [
  1023. ...o,
  1024. Object.assign(option, {
  1025. stdout: this instanceof TaskWrapper ? (_a2 = settings == null ? void 0 : settings.stdout) != null ? _a2 : this.stdout() : process.stdout,
  1026. onCancel: cancelCallback.bind(this, settings)
  1027. })
  1028. ];
  1029. }, []);
  1030. let enquirer;
  1031. if (settings == null ? void 0 : settings.enquirer) {
  1032. enquirer = settings.enquirer;
  1033. } else {
  1034. try {
  1035. enquirer = new (await Promise.resolve().then(() => __toESM(__require("enquirer"), 1))).default();
  1036. } catch (e) {
  1037. this.task.prompt = new PromptError("Enquirer is a peer dependency that must be installed separately.");
  1038. throw new Error(e);
  1039. }
  1040. }
  1041. if (this instanceof TaskWrapper) {
  1042. enquirer.on("prompt", (prompt) => this.task.prompt = prompt);
  1043. enquirer.on("submit", () => this.task.prompt = void 0);
  1044. this.task.subscribe((event) => {
  1045. if (event.type === "STATE" /* STATE */ && event.data === "SKIPPED" /* SKIPPED */) {
  1046. if (this.task.prompt && !(this.task.prompt instanceof PromptError)) {
  1047. this.task.prompt.submit();
  1048. }
  1049. }
  1050. });
  1051. }
  1052. const response = await enquirer.prompt(options);
  1053. if (options.length === 1) {
  1054. return response.default;
  1055. } else {
  1056. return response;
  1057. }
  1058. }
  1059. function destroyPrompt(throwError = false) {
  1060. if (!this.task.prompt || this.task.prompt instanceof PromptError) {
  1061. return;
  1062. }
  1063. if (throwError) {
  1064. this.task.prompt.cancel();
  1065. } else {
  1066. this.task.prompt.submit();
  1067. }
  1068. }
  1069. // src/lib/task-wrapper.ts
  1070. var TaskWrapper = class {
  1071. constructor(task, errors, options) {
  1072. this.task = task;
  1073. this.errors = errors;
  1074. this.options = options;
  1075. }
  1076. get title() {
  1077. return this.task.title;
  1078. }
  1079. set title(data) {
  1080. this.task.title$ = data;
  1081. }
  1082. get output() {
  1083. return this.task.output;
  1084. }
  1085. set output(data) {
  1086. this.task.output$ = data;
  1087. }
  1088. newListr(task, options) {
  1089. let tasks;
  1090. if (typeof task === "function") {
  1091. tasks = task(this);
  1092. } else {
  1093. tasks = task;
  1094. }
  1095. return new Listr(tasks, options, this.task);
  1096. }
  1097. report(error, type) {
  1098. var _a2, _b, _c;
  1099. if (this.task.options.collectErrors !== false) {
  1100. this.errors.push(new ListrError(error, type, this.task));
  1101. }
  1102. this.task.message$ = { error: (_c = (_b = error.message) != null ? _b : (_a2 = this.task) == null ? void 0 : _a2.title) != null ? _c : "Task with no title." };
  1103. }
  1104. skip(message) {
  1105. var _a2, _b;
  1106. this.task.state$ = "SKIPPED" /* SKIPPED */;
  1107. if (message) {
  1108. this.task.message$ = { skip: (_b = message != null ? message : (_a2 = this.task) == null ? void 0 : _a2.title) != null ? _b : "Task with no title." };
  1109. }
  1110. }
  1111. isRetrying() {
  1112. return this.task.isRetrying() ? this.task.retry : { count: 0 };
  1113. }
  1114. async prompt(options) {
  1115. var _a2;
  1116. return createPrompt.bind(this)(options, __spreadValues({}, (_a2 = this.options) == null ? void 0 : _a2.injectWrapper));
  1117. }
  1118. cancelPrompt(throwError = false) {
  1119. return destroyPrompt.bind(this)(throwError);
  1120. }
  1121. stdout() {
  1122. return through((chunk) => {
  1123. chunk = chunk.toString();
  1124. chunk = chunk.replace(new RegExp(CLEAR_LINE_REGEX, "gmi"), "");
  1125. chunk = chunk.replace(new RegExp(BELL_REGEX, "gmi"), "");
  1126. if (chunk !== "") {
  1127. this.output = chunk;
  1128. }
  1129. });
  1130. }
  1131. run(ctx) {
  1132. return this.task.run(ctx, this);
  1133. }
  1134. };
  1135. // src/listr.ts
  1136. var Listr = class {
  1137. constructor(task, options, parentTask) {
  1138. this.task = task;
  1139. this.options = options;
  1140. this.parentTask = parentTask;
  1141. this.tasks = [];
  1142. this.err = [];
  1143. this.renderHook$ = new Subject2();
  1144. this.path = [];
  1145. var _a2, _b, _c;
  1146. this.options = __spreadValues(__spreadValues({}, {
  1147. concurrent: false,
  1148. renderer: "default",
  1149. nonTTYRenderer: "verbose",
  1150. exitOnError: true,
  1151. exitAfterRollback: true,
  1152. collectErrors: "minimal",
  1153. registerSignalListeners: true
  1154. }), options);
  1155. if (this.options.concurrent === true) {
  1156. this.concurrency = Infinity;
  1157. } else if (typeof this.options.concurrent === "number") {
  1158. this.concurrency = this.options.concurrent;
  1159. } else {
  1160. this.concurrency = 1;
  1161. }
  1162. const renderer = getRenderer(this.options.renderer, this.options.nonTTYRenderer, (_a2 = this.options) == null ? void 0 : _a2.rendererFallback, (_b = this.options) == null ? void 0 : _b.rendererSilent);
  1163. this.rendererClass = renderer.renderer;
  1164. if (!renderer.nonTTY) {
  1165. this.rendererClassOptions = this.options.rendererOptions;
  1166. } else {
  1167. this.rendererClassOptions = this.options.nonTTYRendererOptions;
  1168. }
  1169. this.add(task != null ? task : []);
  1170. if (parentTask) {
  1171. this.path = [...parentTask.listr.path, parentTask.title];
  1172. }
  1173. if (this.options.registerSignalListeners) {
  1174. process.once("SIGINT", () => {
  1175. this.tasks.forEach(async (task2) => {
  1176. if (task2.isPending()) {
  1177. task2.state$ = "FAILED" /* FAILED */;
  1178. }
  1179. });
  1180. this.renderer.end(new Error("Interrupted."));
  1181. process.exit(127);
  1182. }).setMaxListeners(0);
  1183. }
  1184. if ((_c = this.options) == null ? void 0 : _c.disableColor) {
  1185. process.env.LISTR_DISABLE_COLOR = "1";
  1186. }
  1187. }
  1188. add(task) {
  1189. const tasks = Array.isArray(task) ? task : [task];
  1190. tasks.forEach((task2) => {
  1191. this.tasks.push(new Task(this, task2, this.options, __spreadValues(__spreadValues({}, this.rendererClassOptions), task2.options)));
  1192. });
  1193. }
  1194. async run(context) {
  1195. var _a2, _b, _c;
  1196. if (!this.renderer) {
  1197. this.renderer = new this.rendererClass(this.tasks, this.rendererClassOptions, this.renderHook$);
  1198. }
  1199. this.renderer.render();
  1200. this.ctx = (_c = (_b = (_a2 = this.options) == null ? void 0 : _a2.ctx) != null ? _b : context) != null ? _c : {};
  1201. await this.checkAll(this.ctx);
  1202. try {
  1203. await pMap(this.tasks, async (task) => {
  1204. await task.check(this.ctx);
  1205. return this.runTask(task, this.ctx, this.err);
  1206. }, { concurrency: this.concurrency });
  1207. this.renderer.end();
  1208. } catch (err) {
  1209. if (this.options.exitOnError !== false) {
  1210. this.renderer.end(err);
  1211. throw err;
  1212. }
  1213. }
  1214. return this.ctx;
  1215. }
  1216. checkAll(context) {
  1217. return Promise.all(this.tasks.map((task) => task.check(context)));
  1218. }
  1219. runTask(task, context, errors) {
  1220. if (!task.isEnabled()) {
  1221. return Promise.resolve();
  1222. }
  1223. return new TaskWrapper(task, errors, this.options).run(context);
  1224. }
  1225. };
  1226. // src/manager.ts
  1227. var Manager = class {
  1228. constructor(options) {
  1229. this.options = options;
  1230. this.err = [];
  1231. this.tasks = [];
  1232. }
  1233. set ctx(ctx) {
  1234. this.options.ctx = ctx;
  1235. }
  1236. add(tasks, options) {
  1237. options = __spreadValues(__spreadValues({}, this.options), options);
  1238. this.tasks = [...this.tasks, this.indent(tasks, options)];
  1239. }
  1240. async runAll(options) {
  1241. options = __spreadValues(__spreadValues({}, this.options), options);
  1242. const ctx = await this.run(this.tasks, options);
  1243. this.tasks = [];
  1244. return ctx;
  1245. }
  1246. newListr(tasks, options) {
  1247. return new Listr(tasks, options);
  1248. }
  1249. indent(tasks, options, taskOptions) {
  1250. options = __spreadValues(__spreadValues({}, this.options), options);
  1251. let newTask;
  1252. if (typeof tasks === "function") {
  1253. newTask = __spreadProps(__spreadValues({}, taskOptions), {
  1254. task: (ctx) => this.newListr(tasks(ctx), options)
  1255. });
  1256. } else {
  1257. newTask = __spreadProps(__spreadValues({}, taskOptions), {
  1258. task: () => this.newListr(tasks, options)
  1259. });
  1260. }
  1261. return newTask;
  1262. }
  1263. async run(tasks, options) {
  1264. options = __spreadValues(__spreadValues({}, this.options), options);
  1265. const task = this.newListr(tasks, options);
  1266. const ctx = await task.run();
  1267. this.err = task.err;
  1268. return ctx;
  1269. }
  1270. getRuntime(pipetime) {
  1271. return `${Math.round(Date.now() - pipetime) / 1e3}s`;
  1272. }
  1273. };
  1274. export {
  1275. Listr,
  1276. ListrError,
  1277. ListrErrorTypes,
  1278. ListrEventType,
  1279. ListrTaskState,
  1280. LogLevels,
  1281. Logger,
  1282. Manager,
  1283. PromptError,
  1284. createPrompt,
  1285. destroyPrompt,
  1286. figures
  1287. };