xprogress 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,1040 +0,0 @@
1
- "use strict";
2
-
3
- var _util = require("util");
4
-
5
- var _lodash = require("lodash");
6
-
7
- var _fs = require("fs");
8
-
9
- var _tty = _interopRequireDefault(require("tty"));
10
-
11
- var _events = _interopRequireDefault(require("events"));
12
-
13
- var _xbytes = _interopRequireDefault(require("xbytes"));
14
-
15
- var _stringd = _interopRequireDefault(require("stringd"));
16
-
17
- var _prettyMs = _interopRequireDefault(require("pretty-ms"));
18
-
19
- var _padRatio = _interopRequireDefault(require("pad-ratio"));
20
-
21
- var _stringdColors = _interopRequireDefault(require("stringd-colors"));
22
-
23
- var _speedometer = _interopRequireDefault(require("speedometer"));
24
-
25
- var _progressStream = _interopRequireDefault(require("progress-stream"));
26
-
27
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
28
-
29
- function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
30
-
31
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
32
-
33
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
34
-
35
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
36
-
37
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
38
-
39
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
40
-
41
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
42
-
43
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
44
-
45
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
46
-
47
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
48
-
49
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
50
-
51
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
52
-
53
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
54
-
55
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
56
-
57
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
58
-
59
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
60
-
61
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
62
-
63
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
64
-
65
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
66
-
67
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
68
-
69
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
70
-
71
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
72
-
73
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
74
-
75
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
76
-
77
- var globOpts = {
78
- bar: {
79
- blank: '-',
80
- filler: '#',
81
- header: '',
82
- colorize: !0,
83
- separator: '',
84
- pulsateSkip: 15,
85
- pulsateLength: 15
86
- },
87
- label: 'Loading',
88
- clean: !1,
89
- // eslint-disable-next-line no-use-before-define
90
- length: 40,
91
- flipper: ['|', '/', '-', '\\'],
92
- pulsate: !1,
93
- template: '',
94
- variables: _objectSpread(_objectSpread({
95
- tag: function tag(_ref) {
96
- var _tag = _ref.tag;
97
- return _tag && typeof _tag !== 'function' ? "".concat(_tag, "\n") : '';
98
- }
99
- }, _stringdColors["default"].raw), {}, {
100
- 'color:bar:empty': ':{color:close}',
101
- 'color:bar:header': ':{color(green)}',
102
- 'color:bar:filled': ':{bgcolor(green)}:{color(black)}',
103
- 'color:bar:separator': ''
104
- }),
105
- forceFirst: !1
106
- };
107
-
108
- var defaultOptions = _objectSpread(_objectSpread({}, globOpts), {}, {
109
- template: ':{tag}[:{bar}] :{flipper} :{label} :3{percentage}% [:{completed}/:{total}]'
110
- });
111
-
112
- var streamOpts = _objectSpread(_objectSpread({}, globOpts), {}, {
113
- pulsate: false,
114
- progress: {
115
- time: 100,
116
- pulsate: false,
117
- infinite: !1,
118
- pulsateSkip: 15,
119
- pulsateLength: 15
120
- },
121
- template: [':{label}', ' |:{slot:bar}| [:3{slot:percentage}%] (:{slot:eta}) [:{speed}] [:{slot:size}/:{slot:size:total}]', ' [:{bar}] [:3{percentage}%] (:{eta}) [:{size}/:{size:total}]'],
122
- variables: _objectSpread(_objectSpread({}, globOpts.variables), {}, {
123
- eta: null,
124
- size: null,
125
- speed: null,
126
- progress: null,
127
- 'eta:raw': null,
128
- 'slot:bar': null,
129
- 'slot:blank': null,
130
- 'slot:eta': null,
131
- 'slot:eta:raw': null,
132
- 'slot:filler': null,
133
- 'slot:header': null,
134
- 'slot:size': null,
135
- 'slot:total': null,
136
- 'slot:runtime': null,
137
- 'slot:runtime:raw': null,
138
- 'slot:percentage': null,
139
- 'slot:size:total': null
140
- }),
141
- stageOpts: {}
142
- });
143
- /**
144
- * Get a persistent tty output stream
145
- * @returns {tty.WriteStream} The writable stream instance similar to `process.stdout`
146
- */
147
-
148
-
149
- function getPersistentStdout() {
150
- var self = getPersistentStdout;
151
- self.stdout = self.stdout && self.stdout.isTTY ? self.stdout : process.stdout.isTTY ? process.stdout : process.stderr.isTTY ? process.stderr : new _tty["default"].WriteStream((0, _fs.openSync)('/dev/tty', 'w'));
152
- return self.stdout;
153
- }
154
- /**
155
- * Get a current flipper
156
- * @param {Number} count Value that determines the flipper
157
- * @param {String|String[]} flippers String or (Array of strigs) of flippers
158
- */
159
-
160
-
161
- var flipper = function getFlipper() {
162
- function subflipper(count, flippers) {
163
- var manageInt = function manageInt(max, val) {
164
- return val > max ? manageInt(max, val - max) : val;
165
- };
166
-
167
- return flippers[manageInt(flippers.length, count) - 1];
168
- }
169
-
170
- return subflipper.count = 0, subflipper;
171
- }();
172
- /**
173
- * Parse a bar, returning a styled bar with a given percentage filled
174
- * @param {_defaultOptions} opts The options for the bar being parsed
175
- * @param {Number} fillable Maximum fillable slots
176
- * @param {Number} percentage Percentage filled
177
- * @param {Boolean} headers Whether or not to add headers to the bar
178
- */
179
-
180
-
181
- function parseBar(opts, fillable, percentage) {
182
- var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : !opts.pulsate;
183
- fillable = Math.round(fillable);
184
- var filled = Math.round(Math.min(100, percentage) / 100 * fillable);
185
- var empty = fillable - filled; // eslint-disable-next-line prefer-const
186
-
187
- var _opts$bar = opts.bar,
188
- filler = _opts$bar.filler,
189
- blank = _opts$bar.blank,
190
- header = _opts$bar.header;
191
-
192
- var _map = [filled, empty].map(Math.floor);
193
-
194
- var _map2 = _slicedToArray(_map, 2);
195
-
196
- filled = _map2[0];
197
- empty = _map2[1];
198
-
199
- var _map3 = [filler, blank].map(function (content) {
200
- return Array.isArray(content) || typeof content === 'string' ? content : '';
201
- });
202
-
203
- var _map4 = _slicedToArray(_map3, 2);
204
-
205
- filler = _map4[0];
206
- blank = _map4[1];
207
- return (0, _stringd["default"])([":{color:bar:filled}".concat(filler.repeat(filled)), ":{color:bar:header}".concat(headers ? header : ''), ":{color:bar:empty}".concat(blank.repeat(empty)), ''].join(':{color:close}:{bgcolor:close}'), opts.variables);
208
- }
209
-
210
- var xprettyMs = function (_) {
211
- return function (sec) {
212
- return Number.isFinite(sec) ? _(sec) : "\u221E";
213
- };
214
- }(_prettyMs["default"]);
215
- /**
216
- * Create a pulsate bar
217
- * @param {ProgressBar} bar The bar to be pulsated
218
- * @param {Array} slots Pulsate slots to be used
219
- * @param {number} skip Valuation for by how much to skip the bar
220
- * @param {string} sep The separator to be used on the bar
221
- */
222
-
223
-
224
- function pulsateBar(bar, slots, skip) {
225
- var sep = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
226
- if (slots[0].level + slots[1].level >= 100) slots[0].level = 100 - slots[1].level;
227
- var total = bar.length() - sep.length * 2;
228
- var stack = [].concat(_toConsumableArray(slots), [{
229
- level: 100 - (slots[0].level + slots[1].level),
230
- value: 0
231
- }]).map(function (_ref2) {
232
- var level = _ref2.level,
233
- value = _ref2.value;
234
- return {
235
- fillable: Math.round(level / 100 * total),
236
- percentage: value
237
- };
238
- });
239
- if (slots[0].level + slots[1].level === 100) slots[0].level = 0;else slots[0].level += skip;
240
- stack[stack.length - 1].fillable += total - Math.min(total, stack.reduce(function (max, _ref3) {
241
- var fillable = _ref3.fillable;
242
- return max + fillable;
243
- }, 0));
244
- return stack.map(function (_ref4) {
245
- var fillable = _ref4.fillable,
246
- percentage = _ref4.percentage;
247
- return parseBar(bar.opts, fillable, percentage, false);
248
- });
249
- }
250
-
251
- var ProgressGen = /*#__PURE__*/function (_EventEmitter) {
252
- _inherits(ProgressGen, _EventEmitter);
253
-
254
- var _super = _createSuper(ProgressGen);
255
-
256
- function ProgressGen() {
257
- _classCallCheck(this, ProgressGen);
258
-
259
- return _super.apply(this, arguments);
260
- }
261
-
262
- return _createClass(ProgressGen);
263
- }(_events["default"]);
264
-
265
- var ProgressBar = /*#__PURE__*/function () {
266
- /**
267
- * Build a progress bar
268
- * @param {Number} total Max attainable value by the progressBar
269
- * @param {((size) => Number|Number[])|Number|Number[]} arr Allocation of slots by value
270
- * @param {_defaultOptions} opts Attachable options
271
- */
272
- function ProgressBar(total) {
273
- var arr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [total];
274
- var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
275
-
276
- _classCallCheck(this, ProgressBar);
277
-
278
- if (!(total && typeof total === 'number')) throw Error('<ProgressBar> must have a max integer value');
279
- if (typeof arr === 'function') arr = arr(total);
280
-
281
- if (_typeof(arr) === 'object' && !Array.isArray(arr)) {
282
- var _ref5 = [[total], arr];
283
- arr = _ref5[0];
284
- opts = _ref5[1];
285
- }
286
-
287
- this.opts = _objectSpread(_objectSpread(_objectSpread({}, defaultOptions), opts), {}, {
288
- bar: _objectSpread(_objectSpread({}, defaultOptions.bar), opts.bar),
289
- variables: _objectSpread(_objectSpread({}, defaultOptions.variables), opts.variables)
290
- });
291
- this.cores = {
292
- total: total,
293
- label: this.opts.label,
294
- append: [],
295
- length: this.opts.length,
296
- stdout: getPersistentStdout(),
297
- pulsateSlots: [[0, 0], [this.opts.bar.pulsateLength, 100]].map(function (_ref6) {
298
- var _ref7 = _slicedToArray(_ref6, 2),
299
- level = _ref7[0],
300
- value = _ref7[1];
301
-
302
- return {
303
- level: level,
304
- value: value
305
- };
306
- })
307
- };
308
- var self = this;
309
- this.slots = (0, _padRatio["default"])(arr, total, false).map(function (max) {
310
- return Object.defineProperties({
311
- max: max,
312
- done: 0
313
- }, {
314
- level: {
315
- get: function get() {
316
- return this.max / self.total() * 100;
317
- },
318
- configurable: true,
319
- enumerable: true
320
- },
321
- percentage: {
322
- get: function get() {
323
- return this.done / this.max * 100;
324
- },
325
- configurable: true,
326
- enumerable: true
327
- }
328
- });
329
- });
330
- delete this.opts.blot;
331
- delete this.opts.label;
332
- delete this.opts.append;
333
- delete this.opts.length;
334
- }
335
- /**
336
- * Label the progressbar while returning itself
337
- * @param {String} label The string label
338
- */
339
-
340
-
341
- _createClass(ProgressBar, [{
342
- key: "label",
343
- value: function label(_label) {
344
- return _label ? (this.cores.label = _label, this) : this.cores.label;
345
- }
346
- /**
347
- * Return or set the max length of the progressbar
348
- * @param {number} [value] The value to set the progressBar length to
349
- */
350
-
351
- }, {
352
- key: "length",
353
- value: function length(value) {
354
- var len = getPersistentStdout().columns;
355
- var core = this.cores.length;
356
-
357
- if (value && ['function', 'number'].includes(_typeof(value))) {
358
- this.cores.length = value;
359
- return this;
360
- }
361
-
362
- var ret;
363
- if (typeof core === 'function') ret = core(len);
364
- if (!ret && typeof core === 'number') ret = core < 0 ? len + core : Math.min(core, 100) / 100 * len;
365
- if (typeof ret !== 'number') throw new Error('length of the bar must be a valid number');
366
- return Math.floor(ret);
367
- }
368
- /**
369
- * Return or update the total level of the progressbar
370
- * @param {number} [value] The number to be added to the total level
371
- * @param {{}} [template] Template variable values to be included into core options
372
- */
373
-
374
- }, {
375
- key: "total",
376
- value: function total(value, template) {
377
- var _this = this;
378
-
379
- if (value && Number.isFinite(value)) {
380
- if (value < this.average().completed) throw new Error("<value> must not be lower than already completed value");
381
- this.slots.map(function (v, r) {
382
- return v.max = (r = v.max, v.max * value / _this.total()), v.done = v.done * v.max / r;
383
- });
384
- this.cores.total = Math.floor(value) ? value : 0;
385
- Object.assign(this.opts.template, template);
386
- return this;
387
- }
388
-
389
- return this.cores.total;
390
- }
391
- /**
392
- * Update the progressbar slots with certain percentages
393
- * - This will top up the current slots with the inputed values as opposed to `this.progress(levels)`
394
- * - The progressbar would be automatically drawn if [template] is provided
395
- * @param {Number|Number[]} levels Level(s) to update the slots with
396
- * @param {{}} [template] Template variable values to use on the drawn progress bar
397
- */
398
-
399
- }, {
400
- key: "tick",
401
- value: function tick(levels, template) {
402
- levels = typeof levels === 'number' ? Array(this.slots.length).fill(levels) : Array.isArray(levels) ? levels : Array(this.slots.length).fill(0);
403
- var res;
404
- return this.percentage(this.slots.map(function (slot, index) {
405
- return res = slot.percentage + Math.floor(levels[index]), res > 100 ? 100 : res;
406
- }), template);
407
- }
408
- /**
409
- * Update the progressbar slots with certain values
410
- * - This will top up the current slots with the inputed values as opposed to `this.progress(levels)`
411
- * - The progressbar would be automatically drawn if [template] is provided
412
- * @param {Number|Number[]} levels Level(s) to update the slots with
413
- * @param {{}} [template] Template variable values to use on the drawn progress bar
414
- */
415
-
416
- }, {
417
- key: "tickValue",
418
- value: function tickValue(levels, template) {
419
- levels = typeof levels === 'number' ? Array(this.slots.length).fill(levels) : Array.isArray(levels) ? levels : Array(this.slots.length).fill(0);
420
- return this.value(this.slots.map(function (slot, index) {
421
- return slot.done + Math.floor(levels[index]);
422
- }), template);
423
- }
424
- /**
425
- * Update the progressbar to a percentage
426
- * - The progressbar would be automatically drawn if [template] is provided
427
- * @param {number|number[]} index The index at which to replace percentage or an array of slot percentages
428
- * @param {number} [value] if (index::number) the percentage for the specified index
429
- * @param {{}} [template] Template variable values to use on the drawn progress bar
430
- * @example
431
- * > this.percentage(50, {}) // Update the entire bar to 50%
432
- * > this.percentage(1, 20, {}) // Set the percentage of the first slot to 20%
433
- * > this.percentage([40,20,70], {}) // Set the percentage of the slots according to array specification
434
- */
435
-
436
- }, {
437
- key: "percentage",
438
- value: function percentage(index, value, template) {
439
- if (this.isEnded) throw Error('This bar has been ended and is now immutable');
440
- var _ref8 = [function (input, msg) {
441
- if (!(Array.isArray(input) ? input : [input]).every(function (v) {
442
- return typeof v === 'number';
443
- })) throw new Error(msg);else return input;
444
- }, function (slots, val, i) {
445
- slots[i].done = parseType(val <= 0 || Math.floor(val) > 100 || val > 100 ? Math.floor(val) : val, "Percentage [".concat(val, "] must be in the range [0 < X < 100]")) / 100 * slots[i].max || slots[i].done;
446
- }],
447
- parseType = _ref8[0],
448
- inferParse = _ref8[1];
449
- var bars = [this].concat(_toConsumableArray(this.cores.append.reduce(function (a, v) {
450
- return v.inherit && a.push(v.bar), a;
451
- }, [])));
452
- if (arguments.length > 1 && value && _typeof(value) !== 'object') parseType([index, value <= 0 || Math.floor(value) > 100 || value > 100 ? Math.floor(value) : value], "<index> and <value> must be of type `number`, <number> must be in the range [0 < X < 100]"), bars.map(function (_ref9) {
453
- var slots = _ref9.slots;
454
- return slots[index].done = value / slots[index].max * 100 || slots[index].value;
455
- });else template = value, bars.map(function (_ref10) {
456
- var slots = _ref10.slots;
457
- return Array.isArray(index) ? index.map(function (val, i) {
458
- return inferParse(slots, val, i);
459
- }) : slots.map(function (_slot, i) {
460
- return inferParse(slots, index, i);
461
- });
462
- });
463
- return !template ? this : this.draw(template);
464
- }
465
- }, {
466
- key: "value",
467
- value: function value(index, _value, template) {
468
- function inferParse(slots, val, i) {
469
- if (val >= 0) {
470
- if (val <= slots[i].max) slots[i].done = val;else throw new Error("Slot index [".concat(i, "] is being updated with more than it can hold [").concat(val, " > ").concat(slots[i].max, "]"));
471
- } else throw new Error("Slot index [".concat(i, "] is being updated with [").concat(val, "] which is less than 0"));
472
- }
473
-
474
- var bars = [this].concat(_toConsumableArray(this.cores.append.reduce(function (a, v) {
475
- return v.inherit && a.push(v.bar), a;
476
- }, [])));
477
- if (arguments.length > 1 && _value && _typeof(_value) !== 'object') bars.map(function (_ref11) {
478
- var slots = _ref11.slots;
479
- return slots[index].done = _value || slots[index].done;
480
- });else template = _value, bars.map(function (_ref12) {
481
- var slots = _ref12.slots;
482
- return Array.isArray(index) ? index.map(function (val, i) {
483
- return inferParse(slots, val, i);
484
- }) : slots.map(function (_slot, i) {
485
- return inferParse(slots, index, i);
486
- });
487
- });
488
- return !template ? this : this.draw(template);
489
- }
490
- /**
491
- * Get an average round up of values in percentage and current progress compatred to the total
492
- * @param {Number} [fixedPoint] The fixed point at which to approximate average values to
493
- * @returns {{completed:number, remaining:number, percentage:number}}
494
- */
495
-
496
- }, {
497
- key: "average",
498
- value: function average(fixedPoint) {
499
- var completed = this.slots.reduce(function (a, b) {
500
- return a + b.done;
501
- }, 0);
502
- var percentage = completed / this.total() * 100;
503
- var remaining = this.total() - completed;
504
-
505
- var _map5 = [percentage, completed, remaining].map(function (value) {
506
- return fixedPoint ? parseFloat(value.toFixed(fixedPoint)) : value;
507
- });
508
-
509
- var _map6 = _slicedToArray(_map5, 3);
510
-
511
- percentage = _map6[0];
512
- completed = _map6[1];
513
- remaining = _map6[2];
514
- return {
515
- completed: completed,
516
- remaining: remaining,
517
- percentage: percentage
518
- };
519
- }
520
- /**
521
- * Draw the progressbar, apply template options to the template
522
- * @param {String|Object} [template] The template to use on the drawn progress bar or an array of predrawn progressbar from `this.constructBar` like `this.oldBar`
523
- */
524
-
525
- }, {
526
- key: "draw",
527
- value: function draw(template) {
528
- var result = Array.isArray(template) ? template : [].concat(_toConsumableArray(this.constructBar(template).split('\n')), _toConsumableArray(this.cores.append.map(function (block) {
529
- return block.bar.constructBar(block.inherit ? template : null);
530
- })));
531
- this.oldBar = result;
532
- this.print("bar".concat(result.length ? "+".concat(result.length - 1) : ''), result.join('\n'));
533
- this.hasBarredOnce = !0;
534
- return this;
535
- }
536
- }, {
537
- key: "constructBar",
538
- value: function constructBar(template) {
539
- var _this2 = this;
540
-
541
- var forcedFirst = [parseBar(this.opts, this.length() - this.opts.bar.header.length, this.average().percentage, this.opts.bar.header)];
542
- var bars = !this.opts.pulsate ? !this.opts.forceFirst ? function () {
543
- var total = Math.max(0, _this2.length() + [[_this2.opts.bar.header, 0], [_this2.opts.bar.separator, -1]].reduce(function (a, _ref13) {
544
- var _ref14 = _slicedToArray(_ref13, 2),
545
- v = _ref14[0],
546
- e = _ref14[1];
547
-
548
- return a - (v.length ? v.length * _this2.slots.length + e : 0);
549
- }, 0));
550
-
551
- var slotting = _this2.slots.map(function (_ref15) {
552
- var level = _ref15.level,
553
- percentage = _ref15.percentage;
554
- return {
555
- portion: Math.floor(level / 100 * total),
556
- percentage: percentage
557
- };
558
- });
559
-
560
- var slack = total - slotting.reduce(function (max, _ref16) {
561
- var portion = _ref16.portion;
562
- return max + portion;
563
- }, 0);
564
- slotting.slice(-1).pop().portion += slack;
565
- var result = slotting.map(function (_ref17) {
566
- var portion = _ref17.portion,
567
- percentage = _ref17.percentage;
568
- return parseBar(_this2.opts, portion, percentage);
569
- });
570
- return result;
571
- }() : forcedFirst : pulsateBar(this, this.cores.pulsateSlots, this.opts.bar.pulsateSkip, this.opts.bar.separator);
572
- var templateString = Array.isArray(this.opts.template) ? this.opts.template.join('\n') : this.opts.template;
573
- var average = this.average();
574
- return this.parseString(templateString, _objectSpread(_objectSpread({
575
- bar: bars.join(":{color:bar:separator}".concat(this.opts.bar.separator, ":{color:close}:{bgcolor:close}")),
576
- 'bar:complete': forcedFirst.join(''),
577
- label: this.label(),
578
- total: this.total(),
579
- flipper: flipper(flipper.count += 1, this.opts.flipper)
580
- }, average), {}, {
581
- percentage: average.percentage.toFixed(0)
582
- }, template));
583
- }
584
- }, {
585
- key: "parseString",
586
- value: function parseString(str, template) {
587
- var variables = _objectSpread({}, template = _objectSpread(_objectSpread({}, this.opts.variables), template));
588
-
589
- Object.entries(this.opts.variables).forEach(function (_ref18) {
590
- var _ref19 = _slicedToArray(_ref18, 2),
591
- spec = _ref19[0],
592
- content = _ref19[1];
593
-
594
- return typeof content === 'function' && content !== template[spec] && (template[spec] = content(template));
595
- });
596
- return (0, _stringd["default"])((0, _stringd["default"])(str, template), variables);
597
- }
598
- /**
599
- * Print a message after a bar `draw` interrupt
600
- * @param {'bar'|'end'} type Type of bar print or the first part of the printer
601
- * @param {any[]} content The contents to be formatted
602
- */
603
-
604
- }, {
605
- key: "print",
606
- value: function print(type) {
607
- var self = this;
608
- type = (0, _util.format)(type);
609
- if (!self.cores.stdout.isTTY) throw Error("Can't draw or print progressBar interrupts with piped output");
610
-
611
- var cleanWrite = function cleanWrite(arr, dontClean) {
612
- var addons = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
613
- var ending = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
614
- var normie = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
615
-
616
- if (!dontClean) {
617
- // check https://github.com/freeall/single-line-log/blob/515b3b99b699396c2ad5f937e4b490b6f9fbff0e/index.js#L1-L3
618
- self.cores.stdout.moveCursor(0, -addons);
619
- self.cores.stdout.cursorTo(0);
620
- self.cores.stdout.clearScreenDown();
621
- }
622
-
623
- (normie ? process.stdout : self.cores.stdout).write("".concat(dontClean && ending && addons ? '\n' : '').concat(self.parseString(_util.format.apply(void 0, _toConsumableArray(arr))).replace(self.opts.bar.colorize ? '' : /\x1b\[\d+m/g, '')));
624
- };
625
-
626
- var addonPack;
627
- var addons = this.hasBarredOnce && !this.justLogged ? this.oldBar.length - 1 : 0;
628
-
629
- for (var _len = arguments.length, content = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
630
- content[_key - 1] = arguments[_key];
631
- }
632
-
633
- this.justLogged = type === 'bar' && content.length === 1 ? !!cleanWrite(content, this.justLogged, addons) : (addonPack = type.match(/^bar\+(\d+)/)) !== null ? !!cleanWrite(content, this.justLogged, this.hasBarredOnce ? addonPack[1] : addons) : type === 'end' ? !!cleanWrite(content, !this.opts.clean, addons, true, true) : !cleanWrite([type.startsWith(':') && "".concat(type.slice(1)) || type].concat(content, ['\n']), this.justLogged, addons, false, true);
634
- if (this.justLogged && this.hasBarredOnce) this.draw(this.oldBar);
635
- return this;
636
- }
637
- /**
638
- * End the bar irrespective of progress, optionally with a message.
639
- * @param {any[]} [message] The message to be printed to `stdout` right before ending the bar
640
- */
641
-
642
- }, {
643
- key: "end",
644
- value: function end() {
645
- if (!this.isEnded) {
646
- for (var _len2 = arguments.length, message = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
647
- message[_key2] = arguments[_key2];
648
- }
649
-
650
- if (message.length) this.print.apply(this, ['end'].concat(message));
651
- this.isEnded = !0;
652
- }
653
-
654
- return this;
655
- }
656
- /**
657
- * Drain all slots in the progressbar to 0
658
- */
659
-
660
- }, {
661
- key: "drain",
662
- value: function drain(slotID) {
663
- if (slotID) this.slots[slotID].done = 0;else this.slots.map(function (slot) {
664
- return slot.done = 0, slot;
665
- });
666
- return this;
667
- }
668
- /**
669
- * Drop the chain, return void
670
- */
671
- // eslint-disable-next-line class-methods-use-this
672
-
673
- }, {
674
- key: "drop",
675
- value: function drop() {}
676
- /**
677
- * Append the specified bar after `this`
678
- * @param {ProgressBar} bar The bar to be appended
679
- * @param {Boolean} inherit Whether or not to inherit bar templates from `this`
680
- */
681
-
682
- }, {
683
- key: "append",
684
- value: function append(bar) {
685
- var inherit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : !1;
686
- if (!ProgressBar.isBar(bar) && !bar.opts.template) throw Error('The Parameter <bar> is not a progressbar or a hanger');
687
- this.cores.append.push({
688
- bar: bar,
689
- inherit: inherit
690
- });
691
- bar.cores.isKid = !0;
692
- return this;
693
- }
694
- /**
695
- * Check if the bar or a slot is complete
696
- * @param {Number} [slot] The slot to be checked for completion
697
- */
698
-
699
- }, {
700
- key: "isComplete",
701
- value: function isComplete(slot) {
702
- if (slot && !this.slots[slot]) throw Error("Value in <slot>:".concat(slot, " has no slot reference"));
703
- return slot ? this.slots[slot].max === this.slots[slot].done : this.average().remaining === 0;
704
- }
705
- /**
706
- * Find out the progressbar is appended to another
707
- */
708
-
709
- }, {
710
- key: "isChild",
711
- get: function get() {
712
- return !!this.cores.isKid;
713
- }
714
- /**
715
- * Check if the progressbar is active.
716
- * - Activity is determined when the progressbar is not complete
717
- */
718
-
719
- }, {
720
- key: "isActive",
721
- get: function get() {
722
- return !this.isComplete();
723
- }
724
- /**
725
- * Check if the bar is fresh.
726
- * - Equivalent of `this.isActive && !this.average().value`
727
- */
728
-
729
- }, {
730
- key: "isFresh",
731
- get: function get() {
732
- return this.isActive && !this.average().completed;
733
- }
734
- /**
735
- * Check if the provided progressbar is an instance of `this`
736
- * @param {ProgressBar} bar The progressbar to be checked
737
- */
738
-
739
- }, {
740
- key: "slotStreamify",
741
- value:
742
- /**
743
- * Prepare a raw generator for use
744
- * @param {(slots:Number, total?:Number) => String} actor The performing function
745
- * @returns {Generator} New ProgressBar Generator
746
- * @yields The through instance or a cache model of the ProgressBar
747
- */
748
- function* slotStreamify(actor, args) {
749
- for (var level = -1; (level += 1) <= (this.opts.progress.infinite ? Infinity : this.slots.length);) {
750
- args = yield !level ? this : ((0, _lodash.merge)(this.opts, args[1]), actor(Math.floor(level - 1), args[0], this.opts.progress.infinite));
751
- }
752
- }
753
- }], [{
754
- key: "isBar",
755
- value: function isBar(bar) {
756
- return bar instanceof ProgressBar;
757
- }
758
- /**
759
- * Check if the provided progressbar is an stream instance of `this`
760
- * @param {ProgressBar} bar The progressbar to be checked
761
- */
762
-
763
- }, {
764
- key: "isBarStream",
765
- value: function isBarStream(barStream) {
766
- return !!barStream && ProgressBar.isBar(barStream.bar) && barStream instanceof _events["default"] && [barStream.read, barStream.write].every(function (slot) {
767
- return typeof slot === 'function';
768
- });
769
- }
770
- /**
771
- * Check if the provided object is a stream progressbar generator
772
- * @param {any} bar The progressbar to be checked
773
- */
774
-
775
- }, {
776
- key: "isBarGen",
777
- value: function isBarGen(barStream) {
778
- return !!barStream && ProgressBar.isBar(barStream.bar) && barStream instanceof _events["default"] && typeof barStream.next === 'function';
779
- }
780
- /**
781
- * Check if the provided object is related to any instances created by this script
782
- * @param {any} bar The progressbar to be checked
783
- */
784
-
785
- }, {
786
- key: "isBarRelated",
787
- value: function isBarRelated(barStream) {
788
- return ProgressBar.isBar(barStream) || ProgressBar.isBarStream(barStream) || ProgressBar.isBarGen(barStream);
789
- }
790
- /**
791
- * Calculate slot levels by number of slots
792
- * @param {number} len Each slot length, inferrable if ratio doesn't make 100 or pop-able if over 100
793
- */
794
-
795
- }, {
796
- key: "slotsByCount",
797
- value: function slotsByCount(len) {
798
- return function (size) {
799
- return (0, _padRatio["default"])(Array(len).fill(size / len), size, false);
800
- };
801
- }
802
- /**
803
- * Calculate slot levels by size
804
- * @param {number} size Maximum possible total size
805
- * @param {number[]} percentages Each slot length, inferrable if ratio doesn't make 100 or pop-able if over 100
806
- */
807
-
808
- }, {
809
- key: "slotsByPercentage",
810
- value: function slotsByPercentage(percentages) {
811
- return function (size) {
812
- return (0, _padRatio["default"])(percentages.map(function (_size) {
813
- return _size / 100 * size;
814
- }), size);
815
- };
816
- }
817
- /**
818
- * Create a streamified bar for use with generators
819
- * @param {Number} total Total attainable value of bytes in <N>
820
- * @param {Number|Number[]} slots Number of slots in <%>
821
- * @param {_streamOpts} [opts] Options for the bar
822
- * @param {(bar:ProgressBar,slotLevel:Number,template:{}) => void} [actor] The actor for every yield
823
- */
824
-
825
- }, {
826
- key: "stream",
827
- value: function stream(total, slots, opts, actor) {
828
- // if (typeof slots === 'function') [slots, opts, actor] = [, {}, slots];
829
- if (typeof opts === 'function') {
830
- var _ref20 = [{}, opts];
831
- opts = _ref20[0];
832
- actor = _ref20[1];
833
- }
834
-
835
- if (_typeof(slots) === 'object' & !Array.isArray(slots)) {
836
- var _ref21 = [, slots];
837
- slots = _ref21[0];
838
- opts = _ref21[1];
839
- }
840
-
841
- opts = _objectSpread(_objectSpread(_objectSpread({}, total === Infinity ? {
842
- pulsate: !0,
843
- template: ':{tag}[:{bar}] [:{flipper}] :{label} (:{slot:runtime}) :{slot:size}'
844
- } : {}), opts), slots === Infinity ? (slots = total, {
845
- progress: {
846
- infinite: !0
847
- }
848
- }) : {});
849
- var progressBar = new ProgressBar(total, slots, opts);
850
- return ProgressBar.streamify(progressBar, actor, opts);
851
- }
852
- /**
853
- * Streamify a bar for use with generators
854
- * @param {ProgressBar} bar The bar to be used
855
- * @param {(bar:ProgressBar, slotLevel:Number, template:() => {completed:number, remaining:number, percentage:number}) => void} [actor] The actor for every yield
856
- * @param {_streamOpts} [opts] Options for the bar
857
- * @returns {{next(size: Number, opts: _streamOpts):NodeJS.WritableStream, bar:ProgressBar}} Returned function from `ProgressBar.streamify`
858
- */
859
-
860
- }, {
861
- key: "streamify",
862
- value: function streamify(bar, actor, opts) {
863
- if (_typeof(actor) === 'object') {
864
- var _ref22 = [, actor];
865
- actor = _ref22[0];
866
- opts = _ref22[1];
867
- }
868
-
869
- bar.opts = (0, _lodash.merge)({}, bar.opts, streamOpts, opts);
870
- bar.opts.template = opts.template || streamOpts.template;
871
- var _ref23 = [[[0, 0], [bar.opts.progress.pulsateLength || bar.opts.bar.pulsateLength, 100]].map(function (_ref24) {
872
- var _ref25 = _slicedToArray(_ref24, 2),
873
- level = _ref25[0],
874
- value = _ref25[1];
875
-
876
- return {
877
- level: level,
878
- value: value
879
- };
880
- }), bar.opts.progress.pulsateSkip || bar.opts.bar.pulsateSkip],
881
- pulsateSlots = _ref23[0],
882
- pulsateSkips = _ref23[1];
883
-
884
- var _defaultUnit;
885
-
886
- var progressGen = new ProgressGen();
887
-
888
- var buildBytesWith = function buildBytesWith(bytes) {
889
- var byteOpts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
890
- return function (props, data) {
891
- return _xbytes["default"].createRelativeSizer(data && (data.args[0] || data.matched.unit) || _defaultUnit, {
892
- iec: data && 'iec' in data.matched ? data.matched.iec === 'true' : byteOpts.iec || !1,
893
- bits: data && 'bits' in data.matched ? data.matched.bits === 'true' : byteOpts.bits || !1,
894
- fixed: data && 'fixed' in data.matched ? parseInt(data.matched.fixed, 10) : byteOpts.fixed || 2,
895
- "short": data && 'short' in data.matched ? data.matched["short"] === 'true' : byteOpts["short"] || !0,
896
- space: data && 'space' in data.matched ? data.matched.space === 'true' : byteOpts.space || !0,
897
- sticky: data && 'sticky' in data.matched ? data.matched.sticky === 'true' : byteOpts.sticky || !1
898
- })(typeof bytes === 'function' ? bytes(props) : bytes);
899
- };
900
- };
901
-
902
- var buildSpeedWith = function buildSpeedWith(speed) {
903
- return function (_, data) {
904
- return "".concat(buildBytesWith(speed, {
905
- iec: !1,
906
- bits: !0,
907
- fixed: 2,
908
- "short": !0,
909
- space: !1,
910
- sticky: !1
911
- })(_, data)).concat(data && data.matched.metric || 'ps');
912
- };
913
- };
914
-
915
- var totalSpeed = (0, _speedometer["default"])(5000);
916
- var streamGenerator = bar.slotStreamify(function (slotIndex, total, infinite) {
917
- var max = !infinite ? Math.round(bar.slots[slotIndex].level / 100 * bar.total()) : Infinity;
918
- total = typeof total === 'function' ? total(bar) : total || max;
919
- if (!infinite && total > max) throw Error("<size> slot must not be greater than maximum possible size for the slot [".concat(max, "], consider using infinite slots"));
920
- var through = (0, _progressStream["default"])(_objectSpread({
921
- length: total
922
- }, bar.opts.progress)).on('progress', function (progress) {
923
- var speed = totalSpeed(progress.delta);
924
-
925
- if (bar.isEnded) {
926
- through.emit('error', Error('The <bar> being used has been ended'));
927
- return;
928
- }
929
-
930
- (actor || function (_bar, args, template) {
931
- return _bar.value.apply(_bar, _toConsumableArray(args)).draw(template);
932
- })(bar, bar.opts.progress.infinite ? [progress.delta + bar.average().completed] : [slotIndex, progress.transferred], {
933
- eta: function eta() {
934
- return xprettyMs(1000 * bar.average().remaining / speed);
935
- },
936
- size: buildBytesWith(function () {
937
- return bar.average().completed;
938
- }),
939
- speed: buildSpeedWith(speed),
940
- 'speed:raw': speed,
941
- 'slot:speed': buildSpeedWith(progress.speed),
942
- 'slot:speed:raw': progress.speed,
943
- progress: progress,
944
- 'eta:raw': function etaRaw() {
945
- return Math.round(bar.average().remaining / speed);
946
- },
947
- 'slot:bar': function slotBar() {
948
- return bar.opts.progress.pulsate ? pulsateBar(bar, pulsateSlots, pulsateSkips, bar.opts.bar.separator).join('') : function () {
949
- var header = bar.opts.bar['slot:header'] || bar.opts.bar.header;
950
- var filler = bar.opts.bar['slot:filler'] || bar.opts.bar.filler;
951
- var blank = bar.opts.bar['slot:blank'] || bar.opts.bar.blank;
952
- return parseBar((0, _lodash.merge)({}, bar.opts, {
953
- bar: {
954
- header: header,
955
- filler: filler,
956
- blank: blank
957
- }
958
- }), bar.length() - (header || '').length, progress.percentage);
959
- }();
960
- },
961
- 'slot:eta': xprettyMs(1000 * progress.eta),
962
- 'slot:eta:raw': progress.eta,
963
- 'slot:size': buildBytesWith(progress.transferred),
964
- 'slot:size:raw': progress.transferred,
965
- 'size:total': buildBytesWith(function () {
966
- return bar.total();
967
- }),
968
- 'slot:runtime': xprettyMs(1000 * progress.runtime),
969
- 'slot:runtime:raw': progress.runtime,
970
- 'slot:percentage': progress.percentage.toFixed(0),
971
- 'slot:size:total': buildBytesWith(progress.length),
972
- 'slot:size:total:raw': progress.length
973
- });
974
- [through, progressGen].map(function (emitter) {
975
- return emitter.emit('tick', {
976
- progress: progress,
977
- bar: bar
978
- });
979
- });
980
- }).on('end', function () {
981
- return bar.isComplete() ? progressGen.emit('complete', bar) : null, progressGen.emit('end', bar);
982
- }).once('error', function (error) {
983
- return bar.end(":{color(red)}[Bar Error]:{color:close} An Error occurred\n".concat(error));
984
- }); // through.emit = (tr => (...args) => (bar.print('tr>', args[0]), tr.call(through, ...args)))(through.emit)
985
-
986
- return through.bar = bar, through;
987
- });
988
- return Object.assign(progressGen, {
989
- /**
990
- * Get the next PassThrough instance
991
- * @param {number} [size] Size for the next chunk (Omittable)
992
- * @param {_streamOpts} [options] Bar options
993
- * @returns {NodeJS.WritableStream} Returned function from `ProgressBar.streamify`
994
- */
995
- next: function next(size, options) {
996
- return streamGenerator.next(_toConsumableArray(typeof size === 'number' ? [size, options] : [, size])).value;
997
- },
998
-
999
- /**
1000
- * End the bar irrespective of progress, optionally with a message.
1001
- * @param {any[]} [message] The message to be printed to `stdout` right before ending the bar
1002
- * @returns {ProgressBar} The ProgressBar
1003
- */
1004
- end: function end() {
1005
- return bar.end.apply(bar, arguments);
1006
- },
1007
-
1008
- /**
1009
- * Print a message after a bar `draw` interrupt
1010
- * @param {any[]} message The message to printed
1011
- * @returns {ProgressBar} The ProgressBar
1012
- */
1013
- print: function print() {
1014
- return bar.print.apply(bar, arguments);
1015
- },
1016
-
1017
- /**
1018
- * Set the default unit
1019
- * @param {xbytes.AllUnitStacks} unit Preferred unit representation
1020
- * @returns {ProgressBar} The ProgressBar
1021
- */
1022
- defaultUnit: function defaultUnit(unit) {
1023
- if (!_xbytes["default"].isUnit(unit)) throw new Error("Invalid ByteString unit: ".concat(unit));
1024
- _defaultUnit = unit;
1025
- return this;
1026
- },
1027
-
1028
- /**
1029
- * The ProgressBar Instance
1030
- * @type {ProgressBar} The ProgresBar
1031
- */
1032
- bar: streamGenerator.next().value
1033
- });
1034
- }
1035
- }]);
1036
-
1037
- return ProgressBar;
1038
- }();
1039
-
1040
- module.exports = ProgressBar;