index.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. 'use strict';
  2. const readline = require('readline');
  3. const chalk = require('chalk');
  4. const cliCursor = require('cli-cursor');
  5. const cliSpinners = require('cli-spinners');
  6. const logSymbols = require('log-symbols');
  7. const stripAnsi = require('strip-ansi');
  8. const wcwidth = require('wcwidth');
  9. const isInteractive = require('is-interactive');
  10. const MuteStream = require('mute-stream');
  11. const TEXT = Symbol('text');
  12. const PREFIX_TEXT = Symbol('prefixText');
  13. const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code
  14. class StdinDiscarder {
  15. constructor() {
  16. this.requests = 0;
  17. this.mutedStream = new MuteStream();
  18. this.mutedStream.pipe(process.stdout);
  19. this.mutedStream.mute();
  20. const self = this;
  21. this.ourEmit = function (event, data, ...args) {
  22. const {stdin} = process;
  23. if (self.requests > 0 || stdin.emit === self.ourEmit) {
  24. if (event === 'keypress') { // Fixes readline behavior
  25. return;
  26. }
  27. if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
  28. process.emit('SIGINT');
  29. }
  30. Reflect.apply(self.oldEmit, this, [event, data, ...args]);
  31. } else {
  32. Reflect.apply(process.stdin.emit, this, [event, data, ...args]);
  33. }
  34. };
  35. }
  36. start() {
  37. this.requests++;
  38. if (this.requests === 1) {
  39. this.realStart();
  40. }
  41. }
  42. stop() {
  43. if (this.requests <= 0) {
  44. throw new Error('`stop` called more times than `start`');
  45. }
  46. this.requests--;
  47. if (this.requests === 0) {
  48. this.realStop();
  49. }
  50. }
  51. realStart() {
  52. // No known way to make it work reliably on Windows
  53. if (process.platform === 'win32') {
  54. return;
  55. }
  56. this.rl = readline.createInterface({
  57. input: process.stdin,
  58. output: this.mutedStream
  59. });
  60. this.rl.on('SIGINT', () => {
  61. if (process.listenerCount('SIGINT') === 0) {
  62. process.emit('SIGINT');
  63. } else {
  64. this.rl.close();
  65. process.kill(process.pid, 'SIGINT');
  66. }
  67. });
  68. }
  69. realStop() {
  70. if (process.platform === 'win32') {
  71. return;
  72. }
  73. this.rl.close();
  74. this.rl = undefined;
  75. }
  76. }
  77. let stdinDiscarder;
  78. class Ora {
  79. constructor(options) {
  80. if (!stdinDiscarder) {
  81. stdinDiscarder = new StdinDiscarder();
  82. }
  83. if (typeof options === 'string') {
  84. options = {
  85. text: options
  86. };
  87. }
  88. this.options = {
  89. text: '',
  90. color: 'cyan',
  91. stream: process.stderr,
  92. discardStdin: true,
  93. ...options
  94. };
  95. this.spinner = this.options.spinner;
  96. this.color = this.options.color;
  97. this.hideCursor = this.options.hideCursor !== false;
  98. this.interval = this.options.interval || this.spinner.interval || 100;
  99. this.stream = this.options.stream;
  100. this.id = undefined;
  101. this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream});
  102. // Set *after* `this.stream`
  103. this.text = this.options.text;
  104. this.prefixText = this.options.prefixText;
  105. this.linesToClear = 0;
  106. this.indent = this.options.indent;
  107. this.discardStdin = this.options.discardStdin;
  108. this.isDiscardingStdin = false;
  109. }
  110. get indent() {
  111. return this._indent;
  112. }
  113. set indent(indent = 0) {
  114. if (!(indent >= 0 && Number.isInteger(indent))) {
  115. throw new Error('The `indent` option must be an integer from 0 and up');
  116. }
  117. this._indent = indent;
  118. }
  119. _updateInterval(interval) {
  120. if (interval !== undefined) {
  121. this.interval = interval;
  122. }
  123. }
  124. get spinner() {
  125. return this._spinner;
  126. }
  127. set spinner(spinner) {
  128. this.frameIndex = 0;
  129. if (typeof spinner === 'object') {
  130. if (spinner.frames === undefined) {
  131. throw new Error('The given spinner must have a `frames` property');
  132. }
  133. this._spinner = spinner;
  134. } else if (process.platform === 'win32') {
  135. this._spinner = cliSpinners.line;
  136. } else if (spinner === undefined) {
  137. // Set default spinner
  138. this._spinner = cliSpinners.dots;
  139. } else if (cliSpinners[spinner]) {
  140. this._spinner = cliSpinners[spinner];
  141. } else {
  142. throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json for a full list.`);
  143. }
  144. this._updateInterval(this._spinner.interval);
  145. }
  146. get text() {
  147. return this[TEXT];
  148. }
  149. get prefixText() {
  150. return this[PREFIX_TEXT];
  151. }
  152. get isSpinning() {
  153. return this.id !== undefined;
  154. }
  155. updateLineCount() {
  156. const columns = this.stream.columns || 80;
  157. const fullPrefixText = (typeof this[PREFIX_TEXT] === 'string') ? this[PREFIX_TEXT] + '-' : '';
  158. this.lineCount = stripAnsi(fullPrefixText + '--' + this[TEXT]).split('\n').reduce((count, line) => {
  159. return count + Math.max(1, Math.ceil(wcwidth(line) / columns));
  160. }, 0);
  161. }
  162. set text(value) {
  163. this[TEXT] = value;
  164. this.updateLineCount();
  165. }
  166. set prefixText(value) {
  167. this[PREFIX_TEXT] = value;
  168. this.updateLineCount();
  169. }
  170. frame() {
  171. const {frames} = this.spinner;
  172. let frame = frames[this.frameIndex];
  173. if (this.color) {
  174. frame = chalk[this.color](frame);
  175. }
  176. this.frameIndex = ++this.frameIndex % frames.length;
  177. const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : '';
  178. const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
  179. return fullPrefixText + frame + fullText;
  180. }
  181. clear() {
  182. if (!this.isEnabled || !this.stream.isTTY) {
  183. return this;
  184. }
  185. for (let i = 0; i < this.linesToClear; i++) {
  186. if (i > 0) {
  187. this.stream.moveCursor(0, -1);
  188. }
  189. this.stream.clearLine();
  190. this.stream.cursorTo(this.indent);
  191. }
  192. this.linesToClear = 0;
  193. return this;
  194. }
  195. render() {
  196. this.clear();
  197. this.stream.write(this.frame());
  198. this.linesToClear = this.lineCount;
  199. return this;
  200. }
  201. start(text) {
  202. if (text) {
  203. this.text = text;
  204. }
  205. if (!this.isEnabled) {
  206. if (this.text) {
  207. this.stream.write(`- ${this.text}\n`);
  208. }
  209. return this;
  210. }
  211. if (this.isSpinning) {
  212. return this;
  213. }
  214. if (this.hideCursor) {
  215. cliCursor.hide(this.stream);
  216. }
  217. if (this.discardStdin && process.stdin.isTTY) {
  218. this.isDiscardingStdin = true;
  219. stdinDiscarder.start();
  220. }
  221. this.render();
  222. this.id = setInterval(this.render.bind(this), this.interval);
  223. return this;
  224. }
  225. stop() {
  226. if (!this.isEnabled) {
  227. return this;
  228. }
  229. clearInterval(this.id);
  230. this.id = undefined;
  231. this.frameIndex = 0;
  232. this.clear();
  233. if (this.hideCursor) {
  234. cliCursor.show(this.stream);
  235. }
  236. if (this.discardStdin && process.stdin.isTTY && this.isDiscardingStdin) {
  237. stdinDiscarder.stop();
  238. this.isDiscardingStdin = false;
  239. }
  240. return this;
  241. }
  242. succeed(text) {
  243. return this.stopAndPersist({symbol: logSymbols.success, text});
  244. }
  245. fail(text) {
  246. return this.stopAndPersist({symbol: logSymbols.error, text});
  247. }
  248. warn(text) {
  249. return this.stopAndPersist({symbol: logSymbols.warning, text});
  250. }
  251. info(text) {
  252. return this.stopAndPersist({symbol: logSymbols.info, text});
  253. }
  254. stopAndPersist(options = {}) {
  255. const prefixText = options.prefixText || this.prefixText;
  256. const fullPrefixText = (typeof prefixText === 'string' && prefixText !== '') ? prefixText + ' ' : '';
  257. const text = options.text || this.text;
  258. const fullText = (typeof text === 'string') ? ' ' + text : '';
  259. this.stop();
  260. this.stream.write(`${fullPrefixText}${options.symbol || ' '}${fullText}\n`);
  261. return this;
  262. }
  263. }
  264. const oraFactory = function (options) {
  265. return new Ora(options);
  266. };
  267. module.exports = oraFactory;
  268. module.exports.promise = (action, options) => {
  269. // eslint-disable-next-line promise/prefer-await-to-then
  270. if (typeof action.then !== 'function') {
  271. throw new TypeError('Parameter `action` must be a Promise');
  272. }
  273. const spinner = new Ora(options);
  274. spinner.start();
  275. (async () => {
  276. try {
  277. await action;
  278. spinner.succeed();
  279. } catch (_) {
  280. spinner.fail();
  281. }
  282. })();
  283. return spinner;
  284. };